用于构建数组的递归函数

时间:2018-03-23 12:57:39

标签: php laravel recursion

有人能看出为什么这不起作用吗?

private static function traverseTree($tree,$node)
{
    $nodes = array();
    $results = array();

    $children = $tree->where('parent_id',$node->id)->where('type',UserGroup::DEPARTMENT_TYPE);

    foreach($children as $child){

        $nodes[] = $child->id;
        $children = self::traverseTree($tree,$child);
        $results = array_merge ($nodes,$children);

    }

    return $results;
}

我正在逐步完成它,我可以看到孩子们已经被发现但是他们没有被包括在最终结果中。

最终结果只包含顶级。

添加了详情: $ tree是一个Laravel Collection,如果我将它传递给我得到的数组:

array (
  0 => 
  array (
    'id' => 21,
    'name' => 'Top',
    'type' => 1,
    'parent_id' => 0,
  ),
  1 => 
  array (
    'id' => 33,
    'name' => 'UKDept',
    'type' => 2,
    'parent_id' => 21,
  ),
  2 => 
  array (
    'id' => 36,
    'name' => 'UKSubDept',
    'parent_id' => 33,
  ),
  3 => 
  array (
    'id' => 37,
    'name' => 'USDept',
    'type' => 2,
    'parent_id' => 21,
  ),
)

$节点:

array (
    'id' => 21,
    'name' => 'Top',
    'type' => 1,
    'parent_id' => 0,
),

填充$ children的第一个调用给出:

array (
  0 => 
  array (
    'id' => 33,
    'name' => 'UKDept',
    'type' => 2,
    'parent_id' => 21,
  ),
  1 => 
  array (
    'id' => 37,
    'name' => 'USDept',
    'type' => 2,
    'parent_id' => 21,
  ),
)

3 个答案:

答案 0 :(得分:0)

尝试在函数外部使用数组。

$nodes = array();
$results = array();

    private static function traverseTree($tree,$node)
    {

        $children = $tree->where('parent_id',$node->id)->where('type',UserGroup::DEPARTMENT_TYPE);

        foreach($children as $child){

            $nodes[] = $child->id;
            $children = self::traverseTree($tree,$child);
            $results = array_merge ($nodes,$children);

        }

        return $results;
    }

每次调用函数时都不会重新初始化它们。检查它是否有效?

答案 1 :(得分:0)

看起来$child是一个数组,但您将其视为一个对象。尝试更改:

$nodes[] = $child->id;

$nodes[] = $child['id'];

答案 2 :(得分:0)

我现在有这个工作,我犯的一个愚蠢的错误是:

foreach($children as $child){

        $nodes[] = $child->id;
        $children = self::traverseTree($tree,$child);
        $results = array_merge ($nodes,$children);

将$ children用作变量名两次!

这是完整的功能:

private static function traverseTree($tree,$node)
{
    $initialId = array();
    $results = array();

    $results[] = $node->id;

    $children = $tree->where('parent_id',$node->id);


    foreach($children as $node){

        //if this is a department, then we need to go deeper
        if($node->type == DEPARTMENT) {
            $nodesChildren = self::traverseTree($tree, $node);
            $results = array_merge ($results,$nodesChildren);
        }else{
            //just add this node to the results array
            $results[] = $node->id;
        }
    }
    return $results;
}