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";
}
}
Added support for arrays to slikts solution
function loop($obj, $path = [])
{
$parent = $path;
if (is_object($obj)) {
foreach ($obj as $key => $value) {
loop($value, array_merge($parent, [$key]));
}
} elseif (is_array($obj)) {
foreach ($obj as $index => $value) {
loop($value, array_merge($parent, [$index]));
}
} else {
echo join('.', $path) . ": $obj" . PHP_EOL;
}
}
Example:
$o = (object) [
"name" => "sample document",
"items" => [
(object) [
"type" => "text",
"placeholder" => "type it"
]
]
];
loop($o);
Outputs:
name: sample document
items.0.type: text
items.0.placeholder: type it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With