Reputation: 1557
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.
Upvotes: 0
Views: 195
Reputation: 10148
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";
}
}
}
Looking at the structure of your object though - recursive iteration may be more readable.
Upvotes: 1
Reputation: 8189
Why don't you just use the get_object_vars()
function ?
see more here : http://php.net/manual/fr/function.get-object-vars.php
Upvotes: 0