PHP递归实现无限级分类并展示

时间:2022-10-24 17:37:38

展示效果
PHP递归实现无限级分类并展示

/** * PHP递归实现无限级分类并展示 */
class getCatListClass {
    public function index(){
        $data[] = ['cat_id'=>1,'cat_name'=>'金融业','parent_id'=>0];
        $data[] = ['cat_id'=>2,'cat_name'=>'证劵/基金','parent_id'=>1];
        $data[] = ['cat_id'=>3,'cat_name'=>'会计/审计/税务','parent_id'=>1];
        $data[] = ['cat_id'=>4,'cat_name'=>'理财与财务服务','parent_id'=>2];
        $data[] = ['cat_id'=>5,'cat_name'=>'建筑/房地产','parent_id'=>0];
        $data[] = ['cat_id'=>6,'cat_name'=>'物业管理/商业中心','parent_id'=>5];
        $data[] = ['cat_id'=>7,'cat_name'=>'房地产','parent_id'=>5];
        $data[] = ['cat_id'=>8,'cat_name'=>'建筑工程','parent_id'=>7];
        $data[] = ['cat_id'=>9,'cat_name'=>'建筑工程1','parent_id'=>8];
        $data[] = ['cat_id'=>10,'cat_name'=>'建筑工程2','parent_id'=>8];

        $arr = $this->getList($data, 0);
        $this->showList($arr);
    }


    /** * 组装成树形结构 * @param $data * @param $pid * @return array */
    private function getList($data, $pid){
        $list = [];
        foreach ($data as $val) {
            if ($val['parent_id'] == $pid) {
                $val['list'] = $this->getList($data, $val['cat_id']);

                if (empty($val['list'])) {
                    unset($val['list']);
                }else{
                    foreach($val['list'] as $key=>$value){
                        $val['list'][$key]['depth'] = $this->getdepth($data,$value['parent_id'],0);
                    }
                }
                $list[] = $val;
            }
        }
        return $list;
    }

    /** * 计算深度 * @param $arr * @param $pid * @param $depth * @return int */
    private function getDepth($data,$pid,$depth){
        foreach($data as $value){
            if(empty($pid)){
                break;
            }
            if($value['cat_id'] == $pid){
                $depth+=1;
                $depth = $this->getDepth($data,$value['parent_id'],$depth);
            }

        }

        return $depth;
    }


    /** * show * @param $list */
    private function showList($list){
        foreach ($list as $val) {
            if(isset($val['depth'])){
                for ($i = 0; $i < $val['depth']; $i++) {
                    echo "——";
                }
            }
            echo $val['cat_name'] . "<br/>";
            if (isset($val['list'])) {
                $this->showList($val['list']);
            }
        }
    }


}