【发布时间】: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