我试图从MySQL结果创建一个多维数组。这是一种亲子关系。像这样。
$navArr = array();
$pageNav = Page::where('parent_id', 0)->orderBy('nav_order', 'asc')->get();
foreach($pageNav as $parent) {
$navArr[$parent->page_id] = $parent;
pageNavChildren = Page::where('parent_id', $parent->page_id)->orderBy('nav_order', 'asc')->get();
if($pageNavChildren) {
foreach($pageNavChildren as $child) {
$navArr[$parent->page_id]['childrens'] = array($child->page_id => $child);
}
}
}
它给了我一个数组,但是数组中只有最后一个子元素。我猜是在循环中写得太多了。我需要一个包含所有父元素的数组如果父元素有子元素则设置子元素键在其中,我需要每个子元素数组在一个键下
修改如下:
if($pageNavChildren) {
foreach($pageNavChildren as $child) {
$navArr[$parent->page_id]['childrens'] = array($child->page_id => $child);
}
}
:
if($pageNavChildren) {
foreach($pageNavChildren as $child) {
$navArr[$parent->page_id]['childrens'][] = array($child->page_id => $child);
}
}