foreach with one item array
15,521
Solution 1
You need:
foreach($category["items"] as $item){
because item
it's just key of first element of array items
.
Solution 2
Remove ["item"]
from foreach loop.
...
foreach($category["items"] as $item){
...
Author by
nebkat
Updated on June 04, 2022Comments
-
nebkat almost 2 years
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" arrays. 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 ) ) )