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

我想简单地从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
————————————————————————————————————————————————————————————————————————

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

解决方法:

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

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

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

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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...