![](/img/trans.png)
[英]Inserting from a multidimensional associative array into multiple tables using PHP and MySQL
[英]PHP/MySQL produce multidimensional associative array from database
编辑
我正在尝试创建一个用于测试目的的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脚本用来自db的数据填充数组:
/**
* 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()
函数转换为递归函数,但在这种情况下不知道如何实现。 有什么建议么?
好的,我认为您的做法正确。 我过去做过类似的事情,除了我没有让父母列出孩子,而是让孩子列出了父母。 我想,从语义上讲,差异很小,但是它将使您的工作变得容易得多。
列出所有没有父项的项目。 这些将是您的主要导航项目。 对于您显示的每个项目,请检查是否有任何行声称此项目为其父项。 如果是这样,则继续并在它们下面列出它们。 这里的所有都是它的!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.