我想通过使用邻接列表模型简单地创建一个多级(三级深)类别层次结构。
分类表:
________________________________________________________________________
| id | parent_id | name | page_order
————————————————————————————————————————————————————————————————————————
| 1 | 0 | Home | 0
| 2 | 0 | sweets | 0
| 3 | 2 | tin sweet | 0
| 4 | 3 | tin rasugulla | 0
| 5 | 2 | kaju katri | 0
| 6 | 2 | ras malai | 0
————————————————————————————————————————————————————————————————————————
我的结果应该是那样的(根据上表):
但我得到的结果却不尽相同:
这是我的codeigniter代码:
public function get_nested(){
// fetching categories from table
$this->db->order_by($this->_order_by);
$pages = $this->db->get($this->_table_name)->result_array();
// now creating category tree
foreach ($pages as $page){
if ($page['parent_id'] == 0){
$array[$page['id']] = $page;
}else {
$array[$page['parent_id']]['children'][$page['id']] = $page;
}
}
return $array;
}
查询结果的快照:var_dump($pages);
快照var_dump($array)
:
这是一个为输出创建列表的代码:
function toUL($array)
{
$html = '<ul>' . PHP_EOL;
foreach ($array as $value)
{
$html .= '<li>' . $value['title'];
// do we have any children?
if (isset($value['children']) && count($value['children'])){
$html .= toUL($value['children']);
}
$html .= '</li>' . PHP_EOL;
}
$html .= '</ul>' . PHP_EOL;
return $html;
}
我上面的代码给了我注意错误:undefined index:title
答案 0 :(得分:0)
问题是你的嵌套代码在$ array中引用了不存在的ID。
对于&#34; tin rasugulla&#34;,parent_id = 3,它不存在于$ array的根级别,因此它会被创建,而实际上它应该尝试找到ID为3的父级,低于&#34;糖果&#34;。
这应该有效:
public function get_nested(){
// fetching categories from table
$this->db->order_by($this->_order_by);
$pages = $this->db->get($this->_table_name)->result_array();
// now creating category tree
foreach ($pages as $page){
if ($page['parent_id'] == 0){
$array[$page['id']] = $page;
} elseif (isset($array[$page['parent_id']])) {
$array[$page['parent_id']]['children'][$page['id']] = $page;
} else {
foreach ($array as $root_id => $parent) {
if (isset($parent['children'][$page['parent_id']])) {
$array[$root_id]['children'][$page['parent_id']]['children'][$page['id']] = $page;
}
}
}
}
return $array;
}