很简单的9行代码实现递归出分类树

实现的数据格式(我已转化为JSON):


[{
    "id": 1,
    "cate_name": "测试分类1",
    "parent_id": 0,
    "sort": 0,
    "create_time": "1970-01-01 08:00:00",
    "child": [
        {
            "id": 5,
            "cate_name": "测试分类1.1",
            "parent_id": 1,
            "sort": 0,
            "create_time": "1970-01-01 08:00:00",
            "child": [
                {
                    "id": 10,
                    "cate_name": "测试分类1.1.1",
                    "parent_id": 5,
                    "sort": 0,
                    "create_time": "1970-01-01 08:00:00",
                    "child": []
                }
            ]
        },
        {
            "id": 9,
            "cate_name": "测试分类1.2",
            "parent_id": 1,
            "sort": 0,
            "create_time": "1970-01-01 08:00:00",
            "child": [
                {
                    "id": 11,
                    "cate_name": "测试分类1.2.1",
                    "parent_id": 9,
                    "sort": 0,
                    "create_time": "1970-01-01 08:00:00",
                    "child": []
                }
            ]
        }
    ]
}]

数据表设计

id bigint     (自增ID)
cate_name      (分类名称)
parent_id         (父级ID)
sort             (排序)
create_time     (创建时间)

实现的代码(我是写在model里的,就直接复制出来了,有需要用自己改)

/**
 * 获取所有分类 树形式
 * @Author 任鹏鹏
 */
public function getAllCateThree($parent_id = 0){
    $index     =    $this->where('parent_id',$parent_id)->select();
    $three     =    [];

    if($index){
        foreach($index as $key => $value){
            $value['child']     =    $this->getAllCateThree($value['id']);
            array_push($three,$value);
        }
    }
    return $three;
}