I have a PHP Object which contains other objects
i.e
$obj->sec_obj->some_var;
I want to use a foreach loop to loop through the object and all objects objects. I think the max level is 3, so
$obj->sec_obj->third_obj->fourth_obj
Any ideas?
I have a PHP Object which contains other objects
i.e
$obj->sec_obj->some_var;
I want to use a foreach loop to loop through the object and all objects objects. I think the max level is 3, so
$obj->sec_obj->third_obj->fourth_obj
Any ideas?
It's just basic recursion.
function loop($obj)
{
if (is_object($obj)) {
foreach ($obj as $x) {
loop($x);
}
} else {
// do something
}
}
Edit: Printing key and value pairs:
function loop($obj, $key = null)
{
if (is_object($obj)) {
foreach ($obj as $x => $value) {
loop($value, $x);
}
} else {
echo "Key: $key, value: $obj";
}
}
Check out this page: http://www.php.net/manual/en/language.oop5.iterations.php
You can use foreach
to loop though the public members of an object, so you could do that with a recursive function.
If you want to be a bit more fancy, you could use an Iterator.
Use a recursive function. A function that calls it's self if the value passed in is an object not the value you're looking for. Careful not to get into an infinite loop though!
here is a good article.