编辑
我正在尝试创建一个用于测试目的的小型 CMS。 我已经设置了一个类,该类根据输出如下所示的数组创建带有嵌套元素的导航:
Array
(
[0] => Array
(
[name] => Home
[link] =>
)
[1] => Array
(
[name] => About us
[link] => about
[children] => Array
(
[0] => Array
(
[name] => Team
[link] => team
)
[1] => Array
(
[name] => History
[link] => history
)
)
)
[2] => Array
(
[name] => Contact
[link] => contact
)
)
到目前为止它工作得很好,但我最终需要的是一个具有无限嵌套可能性的数组。像这样的事情:
Array
(
[0] => Array
(
[name] => Home
[link] =>
)
[1] => Array
(
[name] => About us
[link] => about
[children] => Array
(
[0] => Array
(
[name] => Team
[link] => team
)
[1] => Array
(
[name] => History
[link] => history,
[children] => Array
(
[name] => Pictures
[link] => pictures
)
)
)
)
[2] => Array
(
[name] => Contact
[link] => contact
)
)
我使用以下 PHP 脚本用数据库中的数据填充数组:
/**
* Loops through the children of a page and adds them accordingly to the pages array
*
* @param array $parent
* @param array $children
*/
private function getChildrenPages($parent, $children) {
$subpages = array();
foreach ($children as $child) {
array_push($subpages, array(
'name' => $child['name'],
'link' => $child['link']
));
}
array_push($this->pages, array(
'name' => $parent['name'],
'link' => $parent['link'],
'children' => $subpages
));
}
/**
* @return array Returns an multidimensional associative array with all pages
*/
private function fetchPages() {
// Prevent multiple db fetches
if(!count($this->pages)){
$all_pages = $this->db->get('pages');
for ($i=0; $i < count($all_pages); $i++) {
$parent = $all_pages[$i];
// Get children of current item
$this->db->where('parent_id', $parent['id']);
$children = $this->db->get('pages');
//
if(count($children)) {
$this->getChildrenPages($parent, $children);
}
if (!$parent['parent_id'] && !count($children)) {
// Append current item without children to pages array
array_push($this->pages, array(
'name' => $parent['name'],
'link' => $parent['link']
));
}
}
}
}
这适用于第一级和第二级项目。但是如何处理更高级别的项目呢?我想我必须将 getChildrenPages() 函数转换为递归函数,但不知道在这种情况下如何实现。有什么建议吗?
最佳答案
好吧,我认为你走在正确的道路上。我过去做过类似的事情,只是我让 child 列出 parent ,而不是 parent 列出 child 。我认为语义上的差异很小,但它会让你的事情变得更容易。
列出所有没有父项的项目。这些将是您的主要导航项目。对于您显示的每个项目,检查是否有任何行声明该项目为其父项。如果是这样,请继续将它们列在下面。这就是全部内容!
关于PHP/MySQL 从数据库生成多维关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22693685/