PHP获取下级无限层ID多数用在树形结构和三级分销系统中,其他地方一般比较少用。网上有一部分人是采用循环查询数据库的方式去查询。
原始数组:
- $array = [['id'=>1,'pid'=>0,'name'=>"aa"],['id'=>2,'pid'=>1,'name'=>"bb"],
- ['id'=>3,'pid'=>13,'name'=>"cc"],['id'=>4,'pid'=>14,'name'=>"dd"],
- ['id'=>5,'pid'=>2,'name'=>"ee"],['id'=>6,'pid'=>2,'name'=>"ff"],
- ['id'=>7,'pid'=>13,'name'=>"gg"],['id'=>8,'pid'=>14,'name'=>"aqqa"],
- ['id'=>9,'pid'=>3,'name'=>"ww"],['id'=>10,'pid'=>4,'name'=>"ee"],
- ['id'=>11,'pid'=>5,'name'=>"rr"],['id'=>12,'pid'=>6,'name'=>"tt"],
- ['id'=>13,'pid'=>1,'name'=>"yy"],['id'=>14,'pid'=>1,'name'=>"uu"],
- ['id'=>15,'pid'=>7,'name'=>"124"],['id'=>16,'pid'=>8,'name'=>"fffre"],
- ['id'=>17,'pid'=>9,'name'=>"aef"],['id'=>18,'pid'=>10,'name'=>"erg"],
- ['id'=>19,'pid'=>11,'name'=>"bvg"],['id'=>20,'pid'=>12,'name'=>"fdth"],
- ['id'=>21,'pid'=>13,'name'=>"uyi"],['id'=>22,'pid'=>14,'name'=>"lj"],
- ['id'=>23,'pid'=>0,'name'=>"ii"],['id'=>24,'pid'=>0,'name'=>"pp"],
- ['id'=>25,'pid'=>0,'name'=>"sdfg"],['id'=>26,'pid'=>0,'name'=>"jgh"],
- ['id'=>27,'pid'=>0,'name'=>"ertg"],['id'=>28,'pid'=>0,'name'=>"ghjfghg"]
- ];
递归获取数组中特定ID的所有下级ID:
- public function test(){
- $array = []; //初始数组值
- $data = getJuniorIds(1,$array,'pid');
- var_dump(json_encode($data));
- exit;
- }
- /*
- * 获取下层无限级ID
- */
- function getJuniorIds($parent,$list,$fid='pid'){
- $data = [];
- foreach($list as $item){
- if($item[$fid] == $parent){
- $data[] = $item['id'];
- $data = array_merge($data,getJuniorIds($item['id'],$list,$fid));
- }
- }
- return $data;
- }
最终获得结果:
- 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将数组组合成树形结构》