Find parents key in PHP array

早过忘川 提交于 2021-02-04 16:33:25

问题


I am looking for a method to find all parents of a multidimensional PHP array I have this following array:

Array
(
    [files] => Array
        (
            [a] => Array
                (
                    [ab] => Array
                        (
                            [0] => ab.jpg
                        )

                    [0] => abc.jpg
                )

            [b] => Array
                (
                    [ba] => Array
                        (
                            [bab] => Array
                                (
                                    [0] => abc.jpg
                                )

                            [bac] => Array
                                (
                                    [0] => abd.jpg
                                )

                            [0] => ade.jpg
                        )

                )

            [c] => Array
                (
                    [cb] => Array
                        (
                            [0] => abf.jpg
                        )

                )

        )

)

I want to find Parents by key, for example, To find all parents of key: 'bac'

It should return:

files->b->ba->bac

Any suggestion or example? Help will be much appriciated!

Many thanks!


回答1:


Function:

function array_search_key_recursive($key, array $array) {
    foreach ($array as $i => $child) {
        if ($i === $key) {
            return $i;
        }
        if (!is_array($child)) {
            continue;
        }
        if (false !== $j = array_search_key_recursive($key, $child)) {
            return "{$i}->{$j}";
        }
    }
    return false;
}

Test: http://ideone.com/T2Obqg



来源:https://stackoverflow.com/questions/21515992/find-parents-key-in-php-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!