Monday, 27 August 2018

PHP -Retrieve multidimensional array keys without infinite nested foreach

let's say I have a really complicated multidimensional array like this:
Array
(
        [A] => Array
            (
                [B] => Array
                    (
                        [C] => Array
                            (
                                [D] => Array
                                    (
                                        [E] => Array
                                            (
                                                [0] => Array
                                                    (
                                                        [id] =>
                                                        [firstname] =>
                                                        [lastname] =>
                                                    )

                                            )

                                    )

                            )

                    )

            )

    )

In this array, the number of keys can vary depending on the situation, for example, the keys could be only A, B and C, or only A and B, or even A, B, C, D, E, F, G, H, ... etc. Is it possible to gather the keys (the inner keys A, B, C, D and E in this case) of such array without having 20 nested foreach loops?
So you want to recursively enumerate the keys? Here's a function to do that:
function enumerateKeys($array, &$keys) {
    if(!isset($keys)) {
        $keys = array();
    }

    foreach($array as $key => $value) {
        if(is_array($value)) {
            $keys[] = $key; /* Moved below if() to enumerate only array keys */
            enumerateKeys($value, $keys);
        }
    }
}

0 comments:

Post a Comment