让所有孩子获得深度多维数组

时间:2011-12-28 13:42:43

标签: php arrays recursion multidimensional-array iterator

我有这样的数组:

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
                    )
                )
            )
        )
    )
);

如果有必要,阵列会更深入。我需要让孩子们获得任何特定的身份。

感谢。

4 个答案:

答案 0 :(得分:7)

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;
}

答案 1 :(得分:1)

一种天真的方法是通过从根开始遍历树直到找到节点来进行详尽的search on the tree。在最坏的情况下,您必须迭代整个树只是为了注意您正在寻找的节点是最后一个节点,甚至不存在。

更好的方法是最初构建一个索引,将ID映射到树内的节点上。有了这个,你只需要遍历整个树,然后通过索引直接访问节点。理想情况下,索引将在树结构从平面数据构建期间完成。

因此,如果您有一个像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']];
}

此代码取自my answer to a similar question。您发布的最终数组位于$tree['children']。然后可以使用$index[12345]访问其中的每个节点。

答案 2 :(得分:1)

您可以使用内置代码

$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;
    }
}

答案 3 :(得分:0)

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/