php 获取深度多维数组的所有子元素

zbsbpyhn  于 2023-11-16  发布在  PHP
关注(0)|答案(4)|浏览(158)

我有这样的阵列:

array(
    array(
        'id' => 1,
        'children' => array(
            array(
                'id' => 2,
                'parent_id' => 1
            ),
            array(
                'id' => 3,
                'parent_id' => 1,
                'children' => array(
                    array(
                        'id' => 4,
                        'parent_id' => 3
                    )
                )
            )
        )
    )
);

字符串
如果有必要的话,数组会更深入。我需要得到任何给定id的子元素。
谢谢.

xoefb8l8

xoefb8l81#

function getChildrenOf($ary, $id)
{
  foreach ($ary as $el)
  {
    if ($el['id'] == $id)
      return $el;
  }
  return FALSE; // use false to flag no result.
}

$children = getChildrenOf($myArray, 1); // $myArray is the array you provided.

字符串
除非我遗漏了什么,否则请遍历数组,查找与id键和您要查找的id相匹配的内容(然后将其作为结果返回)。您也可以迭代搜索(并给给予我一秒钟的时间来发布代码,这将检查parentId键).

递归版本,包含子元素:

function getChildrenFor($ary, $id)
{
  $results = array();

  foreach ($ary as $el)
  {
    if ($el['parent_id'] == $id)
    {
      $results[] = $el;
    }
    if (count($el['children']) > 0 && ($children = getChildrenFor($el['children'], $id)) !== FALSE)
    {
      $results = array_merge($results, $children);
    }
  }

  return count($results) > 0 ? $results : FALSE;
}

递归版本,不包括子元素

function getChildrenFor($ary, $id)
{
  $results = array();

  foreach ($ary as $el)
  {
    if ($el['parent_id'] == $id)
    {
      $copy = $el;
      unset($copy['children']); // remove child elements
      $results[] = $copy;
    }
    if (count($el['children']) > 0 && ($children = getChildrenFor($el['children'], $id)) !== FALSE)
    {
      $results = array_merge($results, $children);
    }
  }

  return count($results) > 0 ? $results : FALSE;
}

ojsjcaue

ojsjcaue2#

你可以使用内置的类RecursiveIteratorIterator来实现:

$iter = new RecursiveIteratorIterator(
  new RecursiveArrayIterator($array),
  RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iter as  $val) {
  if (isset($val['id']) && $val['id'] === 3) {
    print_r($val['children']);
    break;
  }
}

字符串

gk7wooem

gk7wooem3#

function array_searchRecursive( $needle, $haystack, $strict=false, $path=array() )
{
    if( !is_array($haystack) ) {
        return false;
    }

    foreach( $haystack as $key => $val ) {
        if( is_array($val) && $subPath = array_searchRecursive($needle, $val,     $strict, $path) ) {
            $path = array_merge($path, array($key), $subPath);
            return $path;
        } elseif( (!$strict && $val == $needle) || ($strict && $val['id'] === $needle) ) {
            $path[] = $key;
            return $path;
        }
    }
    return false;
}

array_searchRecursive( 5, $arr );

字符串
--参考号:http://greengaloshes.cc/2007/04/recursive-multidimensional-array-search-in-php/

7tofc5zh

7tofc5zh4#

一种简单的方法是从根节点开始遍历树,直到找到节点为止。在最坏的情况下,你必须遍历整个树,才能注意到你要找的节点是最后一个节点,或者甚至不存在。
一个更好的方法是首先构建一个索引,将IDMap到树中的节点上。这样,您只需要遍历整个树一次,然后通过索引直接访问节点。理想情况下,索引将在从平面数据构建树结构期间完成。
所以如果你有一个像your other question这样的平面数组,你可以通过一次平面数组的迭代来构建树和索引:

// array to build the final hierarchy
$tree = array(
    'children' => array()
);

// index array that references the inserted nodes
$index = array(0=>&$tree);

foreach ($arr as $key => $val) {
    // pick the parent node inside the tree by using the index
    $parent = &$index[$val['parent_id']];
    // append node to be inserted to the children array
    $node = $val;
    $parent['children'][$val['id']] = $node;
    // insert/update reference to recently inserted node inside the tree
    $index[$val['id']] = &$parent['children'][$val['id']];
}

字符串
这段代码取自我对一个类似问题的回答。你发布的最后一个数组是$tree['children']。其中的每个节点都可以用$index[12345]访问。

相关问题