Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 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

                    )

            )

    )
like image 512
nebkat Avatar asked Feb 15 '26 02:02

nebkat


1 Answers

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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!