Erp系统常用递归,查类目树,查上级,查下级

1、无限极往上获取平台类目树信息

  数据结构:商品类目id《category_id,商品类目父id《parent_id

  数据需求:根据传入最低层类目id,获取所有上级类目信息(包含自己)

  代码如下:

 1     // 无限极往上获取平台类目树信息
 2     public function platformCategoryVerify($platform, $site_code, $platform_category_id, $tree)
 3     {
 4         $apCategories_info = ApCategories::where([['category_id' , $platform_category_id],['platform' , $platform],['site_code' , $site_code]])->first(['category_id', 'category_name', 'parent_id', 'level']);
 5         if(!empty($apCategories_info->category_id)){
 6             $tree[] = $apCategories_info->toArray();
 7             $tree = $this->platformCategoryVerify($platform, $site_code, $apCategories_info->parent_id, $tree); //此处加“$tree = ” 是递归的关键,不然会导致 $tree数组,被覆盖
 8         }
 9         return $tree;
10     }

2、无限极一次性,获取平台类目树信息

  数据结构:商品类目id《category_id,商品类目父id《parent_id

  数据需求:一次性传入整个类目列表,格式化输出,类目树结构,以字段为下级son

  代码如下:

 1     //无限极获取指定类目下所有类目
 2     protected function InfinitusCategory($category_list, $pid)
 3     {
 4         $tree = [];
 5         foreach($category_list as $key => $value){
 6             //父亲找儿子
 7             if($value['category_parent_id'] == $pid){
 8                 $value['son'] = $this->InfinitusCategory($category_list, $value['category_id']);
 9                 $tree[] = $value;
10                 unset($category_list[$key]);
11             }
12         }
13         return $tree;
14     }

 

posted @ 2022-06-14 14:44  在斑马线上散布  阅读(253)  评论(0编辑  收藏  举报
夫人不言,言必有中。这是高级臣僚的一种可贵品质,言辞精炼,直抵要害。