foreach with one item array
I'm making a script that parses an xml and outputs a html form. This is what part of the parsed xml looks like (print_r).
[title] => Base
[id] => base
[type] => radio
[items] => Array
(
[item] => Array
(
[title] => item
[id] => item_id
)
)
This is the code that displays the html output:
foreach($category["items"]["item"] as $item){
echo '<input type="radio" name="'.$category["id"].'" value="'.$item["id"].'">'.$item["title"].'</input><br>';
}
But instead of getting "item" and "item_id" I get "i" on its own for both. Same problem as Array and foreach - Stack Overflow. It works fine when there are two or more "item" ar开发者_JAVA百科rays. Is there any way to fix this without having to make a specific exception for 1 item arrays e.g. if(count($array) == 1) ...
EDIT Here is what a multiple item array looks like:
[title] => K
[id] => k
[type] => radio
[items] => Array
(
[item] => Array
(
[0] => Array
(
[title] => n
[id] => n_id
)
[1] => Array
(
[title] => Y
[id] => y_id
)
)
)
You need:
foreach($category["items"] as $item){
because item
it's just key of first element of array items
.
Remove ["item"]
from foreach loop.
...
foreach($category["items"] as $item){
...
精彩评论