【问题标题】:php getting array levels in the recursionphp在递归中获取数组级别
【发布时间】:2011-05-18 09:42:03
【问题描述】:

我有下一个树数组:

$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); 先感谢您。对不起我的英语。

【问题讨论】:

    标签: php arrays function multidimensional-array


    【解决方案1】:

    您可以将结果数组作为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;
    }
    

    【讨论】:

    • 谢谢。这是一个很好的答案。
    猜你喜欢
    • 2013-11-24
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 2017-12-15
    • 2018-07-30
    • 2021-10-31
    • 2015-03-13
    相关资源
    最近更新 更多