我正在尝试创建导航的多维数组。我的所有页面都在CMS中创建,然后存储在我的数据库中。每个页面都有通常的字段,如title,url等,但是它们也会有一个字段告诉我它是否有任何子节点'p_has_children'以及一个告诉我它的父页面'p_parent'的字段(如果它是一个一页的孩子。)
我以为我可以写一个我可以调用的函数,并向它发送一个包含所有顶级导航项的数组。然后,当我循环遍历每个项目时,我会检查它是否有任何子项,获取子项(并将它们分配给数组),然后通过相同的函数发送它们就像这样....
function sideNavArray()
{
//Get the side navigation
$getSidenav = $this->crud_model->fetch_rows_where('pages', array('p_side_nav' => 'y', 'p_active' => 'y'));
//Call the navbuilder function
$sidenav = $this->sidenavBuilder($getSidenav, 'navitem', 'nav');
//return the generated nav
return $sidenav;
}
function sidenavBuilder($navItems, $itemClass, $navLevel, $i = 0, $sidenav = array())
{
//Loop over each nav item
foreach($navItems as $navItem){
//For each item I want to add th nav_title, slug, url and page type
$sidenav[$i]['p_nav_title'] = $navItem->p_nav_title;
$sidenav[$i]['p_slug'] = $navItem->p_slug;
$sidenav[$i]['p_url'] = $navItem->p_title;
$sidenav[$i]['p_type'] = $navItem->p_type;
//See if this page has any children
if($navItem->p_has_children == 'y'){
//If the page has children then I want to fetch them from the DB
$subnav = $this->crud_model->fetch_rows_where('pages', array('p_parent' => $navItem->id, 'p_active' => 'y', 'p_protected !=' => 'y'));
if(!empty($subnav)){
//Change the item class and level to subnavitem and subnav
$itemClass = 'sub' . $itemClass;
$navLevel = 'sub' . $navLevel;
//Assign the children to the same array as its parent in the "subnav" level and send it through the sitenavBuilder function
$sidenav[$i][$navLevel] = $this->sitenavBuilder($subnav, $itemClass, $navLevel);
}
}
$i++;
//End foreach loop
}
return $sidenav;
}
我相信你们当中有些人现在正在考虑这个问题并且当然说这不会奏效!
我目前正在生成一个导航,但它位于前端,每次我想添加一个额外的级别时,我必须进入代码并手动添加它。我希望避免编写导航的每个级别,因为我希望它能够增长到尽可能多的级别,而不必每次都需要进入并编写额外级别。
我希望这一切都有道理。基本上我想知道是否有办法通过反复运行相同的循环来构建这个nav数组,直到它不再需要为止。