Loop through object containing php object
3 answers
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";
}
}
+9
source to share
Have a look at this page: http://www.php.net/manual/en/language.oop5.iterations.php
You can use foreach
to loop if the public members of the object, so you can do it with a recursive function.
If you want to be a little more quirky, you can use an Iterator.
0
source to share