phpmultidimensional-arrayarray-walk

using array_walk_recursive() for stdClass objects


I have looked through a few answers on here but that don't seem to utilise this method?

I have an array of items, and the items are objects. The object can have a key which is 'children' and 'children' is an array of objects etc.

Is there a way to achieve this?

Example:

    Array
    (
        [1] => stdClass Object
            (
                [id] => 1
                [name] => Steve King
                [image] => upload/shop/fe7a66254e4249af2b0093efca75a914.jpg
                [parent] => 0
                [children] => Array
                    (
                    )

            )

        [2] => stdClass Object
            (
                [id] => 2
                [name] => Eden Hall
                [image] => upload/shop/064f60a98deba612e437ac549f1dc05d.jpg
                [parent] => 0
                [children] =>Array
                    (
                        [1] => stdClass Object
                            (
                              [id] => 1
                              [name] => Steve King
                              [image] => upload/shop/fe7a66254e4249af2b0093efca75a914.jpg
                              [parent] => 0
                              [children] => Array
                                  (
                                  )

                   )
            )
        [3] => stdClass Object
            (
                [id] => 3
                [name] => Paula Johnson
                [image] => upload/shop/1492a323090afbad07c35cf93fe6bdda.jpg
                [parent] => 0
                [children] => Array
                    (
                    )

            )

        [4] => stdClass Object
            (
                [id] => 4
                [name] => Ethan Watson
                [image] => upload/shop/677c720333af33bc58d0684d79918e03.jpg
                [parent] => 0
                [children] => Array
                    (
                    )

            )

        [5] => stdClass Object
            (
                [id] => 5
                [name] => Abigail Adams
                [image] => upload/shop/da1734277322fc3b2e84a9ddbcc2e2f1.jpg
                [parent] => 0
                [children] => Array
                    (
                    )

            )

Solution

  • Assign an array of objects under $array.

    Solution 1: json_encode an array of objects to make it a json and then converting an json into associative array.

    $result=json_decode(json_encode($array),true);
    array_walk_recursive($result, function($value,$key){
        print_r($value);
        print_r($key);
    });
    

    Solution 2: Iterating over array and type casting each object as array.

    array_walk($array,function(&$value,$key){
        $value=(array) $value;
    });
    array_walk_recursive($array, function($value,$key){
        print_r($value);
        print_r($key);
    });