Search code examples
phparrayscounting

PHP - Get all values with specific array key from multidimensional array with unknown depth


I'm currently trying to get all values with a certain key from a multidimensional array with varying depth.

Sadly I'm not really good at dealing with recursion, so I don't really know how to solve this problem on my own. Here's a sample array:

Array
(
    [id] => 243
    [children] => Array
        (
            [0] => Array
                (
                    [id] => 244
                    [children] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 245
                                )

                            [1] => Array
                                (
                                    [id] => 246
                                )

                        )

                )

            [1] => Array
                (
                    [id] => 249
                    [children] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 250
                                )

                        )

                )

            [2] => Array
                (
                    [id] => 253
                    [children] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 256
                                    [children] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [id] => 257
                                                )

                                        )

                                )

                        )

                )

        )

)

I basically just need a simple array with all the ID's from the multidimensional array. In this case the needed result would be:

Array
(
    [0] => 243
    [1] => 244
    [2] => 245
    [3] => 246
    [4] => 249
    [5] => 250
    [6] => 253
    [7] => 256
    [8] => 257
)

I hope somebody can help here.


Solution

  • Remember this forever, keys/indexes must be unique and will be unique always.
    Further, you can use array_walk_recursive to fetch ids from recursive array.

    array_walk_recursive($arr, function($v,$k) use(&$result){
        if($k == 'id') $result[] = $v;
    });
    

    array_walk_recursive — Apply a user function recursively to every member of an array