如何插入嵌套数组数据与父id使用递归函数在php laravel?


{
"items": [
{
"label": "Apricots",
"children": []
},
{
"label": "Blackberries",
"children": []
},
{
"label": "Blueberries",
"children": [
{
"label": "Blackcurrant",
"children": [
{
"label": "Blackcurrant blanc Petits Grains",
"children": []
},
{
"label": "Blackcurrant of Alexandria",
"children": [
{
"label": "Normal",
"children": []
},
{
"label": "Hanepoot",
"children": []
}
]
},
{
"label": "Blackcurrant of Scanzorosciate",
"children": []
}
]
},
{
"label": "Coconut Meat",
"children": []
},
{
"label": "Clementine",
"children": []
},
{
"label": "Cherries",
"children": []
},
{
"label": "Cranberries",
"children": []
}
]
},
{
"label": "Gooseberries",
"children": []
},
{
"label": "Honeydew Melon",
"children": [
{
"label": "Java-Plum",
"children": []
},
{
"label": "Lemon",
"children": []
}
]
}
]
}

这里是嵌套的数组数据,我如何插入父项以及具有父id的子项。我已经尝试了嵌套的foreach循环,但如果子项没有限制,那么我必须循环多少次是不可预测的。请帮我用递归函数来写

首先,选择父记录

$parents = <<Your model>>::where('parent_id',null)->get();

然后循环遍历父元素并递归地填充子元素

foreach ($parents as $key=>$parent){
$parents[$key]["children"] = getChildren($parent->id);
}
function getChildren($parent_id){
$children = <<Your model>>::where('parent_id',$parent_id)->get();
if ($children->count() > 0){
foreach ($children as $key=>$child){
$children[$key]['children'] = getChildren($child->id);
}
}
return $children;
}

最新更新