php在递归中获取数组级别

时间:2010-12-01 09:43:55

标签: php arrays function multidimensional-array

我有下一个树阵列:

$arr = 
array(
 'id' => 1431,
 'children' => array(
  1432 => array(
   'id' => 1432,
   'children' => array(
    1433 => array(
     'id' => 1433,
     'children' => array(),
    ),
    1434 => array(
     'id' => 1434,
     'children' => array(),
    ),
   ) 
  ),
  1435 => array(),
   'id' => 1435,
   'children' => array(
    1436 => array(
     'id' => 1436,
     'children' => array(
      1437 => array(
       'id' => 1437,
       'children' => array(),
      ),
      1438 => array(
       'id' => 1438,
       'children' => array(),
      ),
      1439 => array(
       'id' => 1439,
       'children' => array(),
      ),
     ),
    ),
   ),
 ),
);

我的任务是从这个数组中获取代数组。 我的输出应该是下一个:

Array(
[1] = Array(
  [1432] = ...
  [1435] = ...
),
[2] = Array(
  [1433] = ...
  [1434] = ...
  [1436] = ...
),
[3] = Array(
  [1437] = ...
  [1438] = ...
  [1439] = ...
),
)

但现在我输出了下一个(没有1346元素):

Array(
[1] = Array(
  [1432] = ...
  [1435] = ...
),
[2] = Array(
  [1433] = ...
  [1434] = ...
),
[3] = Array(
  [1437] = ...
  [1438] = ...
  [1439] = ...
),
)

我的功能出了什么问题?

public function getGenerations($userTree, $currGeneration = 0, $result = array())
{
    print_r($userTree);
    $currGeneration++;
    if (!empty($userTree) && !empty($userTree['children'])) {
        foreach($userTree['children'] as $k => $v) {
            $currUser = $v;
            unset($currUser['children']);
            $result[$currGeneration][$k] = $currUser;
            $result += $this->getGenerations($v, $currGeneration, $result);
        }
    }
    return $result;
}

我将此函数称为:$res = getGenerations($arr); 先感谢您。抱歉我的英文。

1 个答案:

答案 0 :(得分:2)

您可以将结果数组作为reference传递,而不是返回,然后将其与本地结果数组连接:

public function getGenerations($userTree, $currGeneration = 0, &$result = array())
{
    print_r($userTree);
    $currGeneration++;
    if (!empty($userTree) && !empty($userTree['children'])) {
        foreach($userTree['children'] as $k => $v) {
            $currUser = $v;
            unset($currUser['children']);
            $result[$currGeneration][$k] = $currUser;
            $this->getGenerations($v, $currGeneration, $result);
        }
    }
    return $result;
}