Search code examples
phpobjectloopsforeach

Iterate though a Object and echo values


I tried a lot of different methods. I managed to get the first part working but the second part to get the fruits name isn't working.

I have an object stored in $food, the print_r() output of this object is shown below:

Food Object
(
    [id] => 1
    [values] => Array
        (
            [name] => Myfood
        )
    [objects] => Array
        (
            [0] => Fruits Object
                (
                    [id] => 1
                    [values] => Array
                        (
                            [name] => My Fruits
                        )
                    [objects] => Array
                        (
                            [0] => FruitType Object
                                (
                                    [id] => 1
                                    [values] => Array
                                        (
                                            [name] => Orange1
                                        )
                                )
                        )
                )
        )
)

This code displays 'Myfood' successfully:

foreach ($food->values as $key => $value) {
    echo "$key => $value";
}

This code displays 'My fruits' successfully:

echo '<br/>';
            
foreach ($food->objects as $id => $owner) {
    foreach ($owner->values as $key => $value) {
        echo "$key => $value";
    }
}
    

I need a second block of code that displays the FruitType object values Orange1, I tried a few things but didn't work out well.


Solution

  • It looks as if you've run into the greatest stumbling block all developers face... naming things. I've probably not done too much better as I'm not 100% sure what your end goal is but you were on the right track as far as nesting loops is concerned.

    foreach ($food->objects as $i => $obj) {
        echo "name => {$obj->values['name']}\n";
        foreach ($obj->objects as $j => $type) {
            foreach($type->values as $key => $val){
                echo "    $key => $val\n";
            }
        }
    }
    

    Working Example

    Looking at the structure of your object though - recursive iteration may be more readable.