【问题标题】:How do I add an array as another array's children, recursively?如何递归地添加一个数组作为另一个数组的孩子?
【发布时间】:2020-12-08 23:55:51
【问题描述】:

我需要建立一个具有父/子关系的对象树。我的对象有一个 parent_id。

public function index()
{
    $root = Project::find($_POST['project_id']);
    $tree = array('name' => $root->name, 'children' => array());
    $this->addChildren($tree, 0, $root->id);
    return response()->json(json_encode($tree));
}

我调用递归函数addChildren()从关系数据库构建树层次结构。

private function addChildren($object, $parent_id, $project_id)
{
    $criterias = Criteria::where([['project_id', '=', $project_id], ['parent_id', '=', $parent_id]])->get();
    foreach($criterias as $criteria) {
        $item = array('name' => $criteria->name, 'children' => array());
        array_push($object['children'], $item);
        if($criteria->has_child)
            $this->addChildren($item, $criteria->id, $criteria->project_id);
    }    
}

但是,当我运行它时,除了在递归 addChildren() 函数之外对其进行的初始推送之外,$tree 对象将返回空对象: {name: "Test Project", children: Array(0)}.

我已经尝试同时推送到 $object['children']

array_push($object['children'], $item);

$object['children'][] = $item;

结果相同。

我知道数据库调用工作正常,因为在 Laravel 调试栏中,我可以看到对数据库的查询与应返回的所有 id 匹配。

【问题讨论】:

  • 你需要返回一些东西:return $this->addChildren(...) 否则递归将没有更新的值可以使用。
  • 你能提供一个简短的例子吗?我尝试返回函数调用但没有成功。
  • $tree = $this->addChildren($tree, 0, $root->id); .. 然后在你的函数中使用return。递归是在你的应用程序中做事的一种很酷的方式,我想你可以找到一些教程来了解它是如何工作的。

标签: php recursion multidimensional-array laravel-7 array-push


【解决方案1】:

我在 Felippe Duarte 的评论的帮助下修复了问题。向函数添加返回值并将该值设置为数组就可以了。

$tree['children'] = $this->addChildren(0, $root->id);

private function addChildren($parent_id, $project_id)
{
    $criterias = Criteria::where([['project_id', '=', $project_id], ['parent_id', '=', $parent_id]])->get();
    $children = [];
    foreach($criterias as $criteria) {
        $item = array('name' => $criteria->name, 'children' => array());            
        if($criteria->has_child) {
            $item['children'] = $this->addChildren($criteria->id, $criteria->project_id);    
        }
        array_push($children, $item);        
    }
    return $children;
}

【讨论】:

    猜你喜欢
    • 2016-08-16
    • 2012-08-24
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 2014-10-24
    相关资源
    最近更新 更多