Fork me on Baidu

无限极分类

来源 :https://www.cnblogs.com/hualingyun/p/16364375.html

private function getChildBak($data,$parent_id = 0){
        $arr=array();
        $i = 0; 
        foreach($data as $val){ 
            if($val['pId']==$parent_id){ 
    
                $val['label'] = $val['name'];
                $arr[$i]=$val;
                $son=$this->getChildBak($data,$val['id']);
                $arr[$i]['children']=$son;
                $i++;
            }
        }
        return $arr;
    }

 

    private function buildTree(array $categories, int $parentId = 0, int $level = 0): array
    {
        $tree = [];
        foreach ($categories as $category) {
            if ($category['parent_id'] == $parentId) {
                // 添加层级信息
                $category['level'] = $level;
                // 递归查找子分类
                $children = $this->buildTree($categories, $category['id'], $level + 1);
                if ($children) {
                    $category['children'] = $children;
                }
                $tree[] = $category;
            }
        }
        return $tree;
    }

  

 
posted @ 2023-10-19 11:19  consideration  阅读(27)  评论(0)    收藏  举报