开发者

looping through a object which contains an object php

开发者 https://www.devze.com 2022-12-08 08:55 出处:网络
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

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.

http://devzone.zend.com/article/1235


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
0

精彩评论

暂无评论...
验证码 换一张
取 消