doulan1866 2015-11-30 16:16
浏览 44

返回嵌套数组的所有键

given a nested array of arbitrary depth like this:

$array = array(
            1400=> 
                array(7300=>
                        array(
                            7301=> array(),
                            7302=> array(),
                            7305=> array(
                                7306=>array()
                            ),
                        ),
                    7314=>array()
                ),
            );

how would one get the hierarchy of keys for any key.

for example:

getkeys(7305);

should return 1400,7300,7305 in that order

or

getkeys(7314);

should return 1400,7314

all array keys are unique values

  • 写回答

3条回答 默认 最新

  • dpwdsmbvm496180204 2015-11-30 17:29
    关注

    The idea is to check current array branch, and if the needle key isn't found, then iterate current items and check their array child nodes by recursive function calls. Before each step down we push a current key to stack, and pop the stack if the function does not found a needle key in whole branch. So if the key found, the function returns true by the chain, preserving successful keys in the stack.

    function branchTraversing(& $branch, & $key_stack, $needle_key) {
      $found = false;
      if (!array_key_exists($needle_key, $branch)) {
        reset($branch);
        while (!$found && (list($key, $next_branch) = each($branch))) {
          if (is_array($next_branch)) {
            array_push($key_stack, $key);
            $found = branchTraversing($next_branch, $key_stack, $needle_key);
            if (!$found) {
              array_pop($key_stack);
            }
          }
        }
      } else {
        array_push($key_stack, $needle_key);
        $found = true;
      }
    
      return $found;
    }
    
    function getPath(& $array, $needle_key) {
      $path = [];
      branchTraversing($array, $path, $needle_key);
      return $path;
    }
    
    $test_keys = [1400, 7300, 7302, 7306, 7314, 666];
    
    foreach ($test_keys as $search_key) {
      echo '<p>' . $search_key . ' => [ '
      . implode(', ', getPath($array, $search_key)) . ' ]</p>';
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等