php按键从数组中获取子数组

Ale*_*tau 0 php arrays recursion

我有下一个层次结构数组:

Array(
[1005] => Array(
               [1000] => Array(
                              [1101] => ...
                              [1111] => ...
                              )
               )
)
Run Code Online (Sandbox Code Playgroud)

在我的功能中,我发送$ Id.我的任务是通过此Id返回一个数组.例如:getArray(1000)应该返回下一个数组:

Array(
                                  [1101] => ...
                                  [1111] => ...
                                  )
Run Code Online (Sandbox Code Playgroud)

我该怎么做?谢谢.

Gum*_*mbo 5

这是一个递归实现getArray:

function getArray($array, $index) {
    if (!is_array($array)) return null;
    if (isset($array[$index])) return $array[$index];
    foreach ($array as $item) {
        $return = getArray($item, $index);
        if (!is_null($return)) {
            return $return;
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

这是一个迭代实现getArray:

function getArray($array, $index) {
    $queue = array($array);
    while (($item = array_shift($queue)) !== null) {
        if (!is_array($item)) continue;
        if (isset($item[$index])) return $item[$index];
        $queue = array_merge($queue, $item);
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)