PHP递归获取最上级和所有子级
- PHP
- 2024-07-19
- 244热度
- 0评论
在做PHP开发的过程中,经常会需要获取最上级或所有子级的应用场景:
获取最顶级
$list = [
['id'=>1,'pid'=>0,'name'=>'张飞'],
['id'=>2,'pid'=>1,'name'=>'张苞'],
['id'=>3,'pid'=>2,'name'=>'张遵'],
['id'=>4,'pid'=>3,'name'=>'张三'],
['id'=>5,'pid'=>3,'name'=>'张四'],
];
$parent = getParent($list,5);
var_dump($parent);
function getParent($list,$id){
foreach($list as $item) if($id == $item['id']) $citem = $item; // 当前
if(!$citem['pid']) return $citem; // 它没有上级,则它本身就是最上级
return getParent($list,$citem['pid']);
}
获取所有子级
$list = [
['id'=>1,'pid'=>0,'name'=>'张飞'],
['id'=>2,'pid'=>1,'name'=>'张苞'],
['id'=>3,'pid'=>2,'name'=>'张遵'],
['id'=>4,'pid'=>3,'name'=>'张三'],
['id'=>5,'pid'=>3,'name'=>'张四'],
];
$childs = getChilds($list,1);
var_dump($childs);
var_dump(array_column($childs,'id'));
function getChilds($list,$id){
$childs = [];
foreach($list as $item){
if($id == $item['pid']){
$childs[] = $item;
$childs = array_merge($childs,getChilds($list,$item['id']));
}
}
return $childs;
}