Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping through a object which contains an object php

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?

like image 444
dotty Avatar asked Mar 12 '26 12:03

dotty


2 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";
    }
}
like image 131
slikts Avatar answered Mar 15 '26 02:03

slikts


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
like image 29
ajthinking Avatar answered Mar 15 '26 03:03

ajthinking