ThinkPHP6使用递归生成栏目树的方法
作者:韩明剑
时间:2021-04-08
浏览:1222
点赞:0

需求分析:ThinkPHP6通过递归函数实现栏目无限分级,并形成栏目树

数据库表:

hcms_category_main(栏目主表)hcms_category_type(栏目类型表)
idididid
name名称order_id排序id
folder目录name名称
upcateid上级栏目id  
sort排序  
type类型  
keyword关键字  
description描述  

实现代码:

function categoryTree($level=1,$typeid=0,$upcateid = 0){
    if($typeid != 0){
        $map[] = ['m.type','=',$typeid];
    }

    $map[] = ['upcateid','=',$upcateid];
    $resTop = Db::name('category_main')
        ->field('m.id,m.name as cate_name,t.name as type_name,m.type as type_id')
        ->alias('m')
        ->leftJoin('category_type t','m.type=t.order_id')
        ->where($map)
        ->order('m.sort','asc')
        ->select();
    $cateTree=array();
    $count=count($resTop);
    $i=0;
    foreach($resTop as $v)
    {
        $i++;
        if($count==$i) {
            $step="└─ ";
        } else {
            $step="├─ ";
        }
        $nbsp=str_repeat("  ",$level-1);
        $cateTree[$i]['id'] = $v['id'];
        $cateTree[$i]['cate_name'] = $nbsp.$step.$v['cate_name'];
        $cateTree[$i]['type_name'] = $v['type_name'];
        $cateTree[$i]['type_id'] = $v['type_id'];
        $cateTree[$i]['child'] = categoryTree($level+1,$typeid,$v['id']);
    }
    return $cateTree;
}

原创不易,转载请保留本站版权。