下面的示例用于填充树并使用带有parent_id列的表。
数据是通过递归查询获得的。
$data = [{
"id": 1,
"name": "parent 1"
"note": "note 1",
}, {
"id": 2,
"name": " parent 2",
"note": "note 2",
"children": [{
"id": 21,
"name": "child A of 2",
"note": "note A of 2",
},{
"id": 22,
"name": "child B of 2",
"note": "note B of 2",
},{
"id": 23,
"name": "child C of 2",
"note": "note C of 2",
"children": [{
"id": 231,
"name": "child A of 23",
"note": "note A of 23",
"children": [{
"id": 2311,
"name": "child A of 231",
"note": "note A of 231",
"children": []
}]
}]
}]
}];
和查询:
$myData= Hierarchy::whereNull('parent_id')
->with('children')
->get();
一切顺利。
要解决的问题:
需要获取父节点和子节点的id和name属性的简单(非分层)列表。
的例子:
"id": 1,
"name": "parent 1",
"id": 2,
"name": " parent 2",
"id": 21,
"name": "child A of 2",
"id": 23,
"name": "child C of 2",
"id": 231,
"name": "child A of 23",
"id": 2311,
"name": "child A of 231"
虽然这可以用javascript在客户端解决,但我打算用雄辩或PHP函数来解决。
我尝试了array_walk()和array_walk_recursive() PHP函数(没有成功)。
是否有办法解决雄辩,记住,子节点的数量可以是无限的?
谢谢。
编辑:
array_walk_recursive() PHP函数
public function getList()
{
$myData= Hierarchy::whereNull('parent_id')
->with('children')
->get();
$data = array_walk_recursive($myData, "self::myFunction");
return response()->json(['success' => true, "data" => $data]);
}
public function myFunction($item, $key){
???
}
您可以递归地使用API资源或使用递归函数来生成层次数组。
的例子递归功能:
function makeHierarchy($values)
{
$result = [];
foreach($values as $item) {
$result[] = [
'id' => $item->id,
'name' => $item->name,
'children' => makeHierarchy($item->children),
];
}
return $result;
}
$values = Hierarchy::whereNull('parent_id')->with('children')->get();
$hierarchical = makeHierarchy($values);
如果你想获得所有的值作为一个平面列表:
$values = Hierarchy::get();
$result = [];
foreach($values as $item) {
$result[] = [
'id' => $item->id,
'name' => $item->name,
];
}
# now the result contains all the parents and children in a flat list
用更干净的方式:
$result = Hierarchy::select(['id', 'name'])->all();