如何创建多级别类别层次结构(类别树) - codeigniter

AZi*_*key 4 php mysql categories

我想简单地从mysql创建一个多级类别层次结构

分类表:

________________________________________________________________________
| id              |  parent_id     | name
————————————————————————————————————————————————————————————————————————
| 1               |  0             | Root
| 2               |  1             | Sub category of root
| 3               |  0             | category 1
| 4               |  3             | sub category of category 1
| 5               |  4             | sub category of first sub category of category 1
————————————————————————————————————————————————————————————————————————
Run Code Online (Sandbox Code Playgroud)

PHP

public function getCategoryTree($level = 0) {
    $rows = $this->db
            ->select(‘id,parent_id,name’)
            ->where(‘parent_id’, $level)
            ->get(‘categories’)
            ->result();

    if (count($rows) > 0) {
        foreach ($rows as $row) {
            $rows = $this->getCategoryTree($row->id);
        }
    }
  //return $rows;
}


echo $rows;

// output will be show as string so i have to return this string in a variable

Root
—Sub category of root
category 1
—sub category of category 1
——sub category of first sub category of category 1
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 7

代码中最大的问题是你$rows在foreach循环中覆盖了.

另外,使用递归解决方案,就像你已经去过的那样,跟踪从函数/方法的内部调用返回的内容非常重要.

另外,我添加了一个订单,以确保首先显示根类别.

protected function getCategoryTree($level = 0, $prefix = '') {
    $rows = $this->db
        ->select('id,parent_id,name')
        ->where('parent_id', $level)
        ->order_by('id','asc')
        ->get('categories')
        ->result();

    $category = '';
    if (count($rows) > 0) {
        foreach ($rows as $row) {
            $category .= $prefix . $row->name . "\n";
            // Append subcategories
            $category .= $this->getCategoryTree($row->id, $prefix . '-');
        }
    }
    return $category;
}

public function printCategoryTree() {
    echo $this->getCategoryTree();
}
Run Code Online (Sandbox Code Playgroud)