PHP获取下级无限层ID源码分享

PHP获取下级无限层ID多数用在树形结构和三级分销系统中,其他地方一般比较少用。网上有一部分人是采用循环查询数据库的方式去查询。

原始数组:

  1. $array = [['id'=>1,'pid'=>0,'name'=>"aa"],['id'=>2,'pid'=>1,'name'=>"bb"],
  2.             ['id'=>3,'pid'=>13,'name'=>"cc"],['id'=>4,'pid'=>14,'name'=>"dd"],
  3.             ['id'=>5,'pid'=>2,'name'=>"ee"],['id'=>6,'pid'=>2,'name'=>"ff"],
  4.             ['id'=>7,'pid'=>13,'name'=>"gg"],['id'=>8,'pid'=>14,'name'=>"aqqa"],
  5.             ['id'=>9,'pid'=>3,'name'=>"ww"],['id'=>10,'pid'=>4,'name'=>"ee"],
  6.             ['id'=>11,'pid'=>5,'name'=>"rr"],['id'=>12,'pid'=>6,'name'=>"tt"],
  7.             ['id'=>13,'pid'=>1,'name'=>"yy"],['id'=>14,'pid'=>1,'name'=>"uu"],
  8.             ['id'=>15,'pid'=>7,'name'=>"124"],['id'=>16,'pid'=>8,'name'=>"fffre"],
  9.             ['id'=>17,'pid'=>9,'name'=>"aef"],['id'=>18,'pid'=>10,'name'=>"erg"],
  10.             ['id'=>19,'pid'=>11,'name'=>"bvg"],['id'=>20,'pid'=>12,'name'=>"fdth"],
  11.             ['id'=>21,'pid'=>13,'name'=>"uyi"],['id'=>22,'pid'=>14,'name'=>"lj"],
  12.             ['id'=>23,'pid'=>0,'name'=>"ii"],['id'=>24,'pid'=>0,'name'=>"pp"],
  13.             ['id'=>25,'pid'=>0,'name'=>"sdfg"],['id'=>26,'pid'=>0,'name'=>"jgh"],
  14.             ['id'=>27,'pid'=>0,'name'=>"ertg"],['id'=>28,'pid'=>0,'name'=>"ghjfghg"]
  15.         ];

递归获取数组中特定ID的所有下级ID:

  1. public function test(){
  2.         $array = [];  //初始数组值
  3.         $data = getJuniorIds(1,$array,'pid');
  4.         var_dump(json_encode($data));
  5.         exit;
  6.     }
  7. /*
  8.  * 获取下层无限级ID
  9.  */
  10. function getJuniorIds($parent,$list,$fid='pid'){
  11.     $data = [];
  12.     foreach($list as $item){
  13.         if($item[$fid] == $parent){
  14.             $data[] = $item['id'];
  15.             $data = array_merge($data,getJuniorIds($item['id'],$list,$fid));
  16.         }
  17.     }
  18.     return $data;
  19. }

最终获得结果:

  1. string(56) "[2,5,11,19,6,12,20,13,3,9,17,7,15,21,14,4,10,18,8,16,22]"

可以看出从2~22都是1的下级,按照顺序获得了下级的ID。如需获取下级树形结构可参考菠菜园《PHP将数组组合成树形结构

你想把广告放到这里吗?

发表评论

您必须 登录 才能发表留言!