php无限级分类

php无限级分类


type_id 分类id
pid 父级id
lev 等级

/*
     * 树
     * $third是否要第三层权限
     */
    public static function convert_tree($arr=[], $layer=true, $third=true, $indent=true){
     
        $tree=[];
        $refer = [];
        //获取顶级
        foreach($arr as $k => $v){
     
            $arr[$k]['hasSub'] = 0;
            $refer[$v['type_id']] = & $arr[$k]; //创建主键的数组引用
        }
        foreach($arr as $k => $v){
     
            //获取当前栏目的父级id
            $pid=$v['pid'];
            if ($pid==0){
     
                //判断是否为顶级
                $arr[$k]['lev'] = 0;
                $tree[] = & $arr[$k];  //顶级栏目
            }else{
     
                if(isset($refer[$pid]['lev'])){
     
                    $lev = $refer[$pid]['lev'] + 1;
                    $arr[$k]['lev'] = $lev;
                    if ($indent) {
     
                        $arr[$k]['type_name'] = str_repeat('-', $arr[$k]['lev']*2).'├'.$arr[$k]['type_name'];
                    }
                    //无层级结构
                    //如果打开if判断就是三级分类,注释掉就是无限级分类
                    //if (1 == $lev || (2 == $lev && $third)) {
     
                        foreach($tree as $g=>$h) {
     
                            if ($h['type_id'] == $pid) {
     
                                array_splice($tree, $g+1, 0, [$arr[$k]]);
                            }
                        }
                    //}
                }
            }
        }
        return $tree;
    }

你可能感兴趣的:(php)