无极分类之子孙树、父辈树
<?php function subTree($arr, $id=0, $depth=0) { static $tree = array(); foreach ($arr as $key=>$value) { if($value['father_id'] == $id) { $value['depth'] = $depth; $tree[] = $value; subTree($arr, $value['id'], $depth+1); //tree($arr, $value['id'],$depth+1); } } return $tree; } function fatherTree($arr,$id) { static $list = array(); foreach($arr as $v) { if($v['id'] == $id) { fatherTree($arr,$v['father_id']); $list[] = $v; } } return $list; } $arr = [ ['id'=>1,'name'=>'news','father_id'=>0], ['id'=>2,'name'=>'article','father_id'=>0], ['id'=>3,'name'=>'local news','father_id'=>1], ['id'=>4,'name'=>'good article','father_id'=>2], ['id'=>5,'name'=>'bad article','father_id'=>2], ['id'=>6,'name'=>'sea','father_id'=>4], ]; $tree = subTree($arr); foreach($tree as $v){ echo str_repeat('----',$v['depth']).$v['name'].$v['depth'].'<br>'; } $list = fatherTree($arr,6); foreach ($list as $key => $value) { echo $value['name'].'>>'; }