3

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 ) ) ) 
3
  • 3
    remove the ["item"] in foreach($category["items"]["item"] ;) Commented Jun 7, 2011 at 17:25
  • seems to be working here: codepad.org/PZGbM5Ag Commented Jun 7, 2011 at 17:26
  • BTW: you get "i" because it's the first character of "item" in [title] ("id" converts to 0). Commented Jun 7, 2011 at 17:40

2 Answers 2

8

You need:
foreach($category["items"] as $item){
because item it's just key of first element of array items.

Sign up to request clarification or add additional context in comments.

6 Comments

I know that will work for this, but what about when there are multiple $category["items"]["item"]s?
@Neb: what does your array look like with multiple [item]'s? Because PHP cannot use the same key twice ;)
@Neb, it will work for multiple. I think you not got yet how foreach works. foreach takes array (not first element) as argument, and iterates each element.
Edited first post. I can see the difference between multiple and single, but in the xml file they are both written the same way. Maybe my only option is to modify the xml parser to generate $category["items"]["item"]["0"] even with one item only?
@Neb, well... it's another structure now. Define, which structure do you have to get correct answer for your case.
|
3

Remove ["item"] from foreach loop.

... foreach($category["items"] as $item){ ... 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.