面对多级类别层次结构中的一些问题

Facing some issues in multi level category hierarchy

我想使用邻接表模型简单地创建一个多级(三级深)类别层次结构。

类别table:

________________________________________________________________________
| 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
————————————————————————————————————————————————————————————————————————

我的结果应该是这样的(根据上面table):

但我得到的输出略有不同:

这是我的 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;
}

我上面的代码给我通知错误:未定义索引:标题

问题是您的嵌套代码引用了 $array 中不存在的 ID。

对于 "tin rasugulla",parent_id = 3,它不存在于 $array 的根级别,所以它被创建,而实际上它应该尝试找到 ID 为 3 的父级,低于 "sweets".

这应该有效:

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;
}