百度都是一個抄一個,誰抄誰的也不知道,對我沒有一點用,最終我也了一個,改造了一下,跑的通
最終截圖
代碼 代碼可直接複製,可以直接運行, 最後訪問的 接口是 如:127.0.0.1:**/index/index/getDg
class Index
{
private static function arr(){
$rows = array(
array(
'id'=>'1',
'name'=>'一級菜單',
'pid'=>'0',
'path'=>'0',
),
array(
'id'=>'2',
'name'=>'二級菜單',
'pid'=>'0',
'path'=>'0',
),
array(
'id'=>'3',
'name'=>'一級菜單-1',
'pid'=>'1',
'path'=>'0-1',
),
array(
'id'=>'4',
'name'=>'二級菜單-1',
'pid'=>'2',
'path'=>'0-2',
),
array(
'id'=>'5',
'name'=>'一級菜單-1-1',
'pid'=>'3',
'path'=>'0-1-3',
),
array(
'id'=>'6',
'name'=>'二級菜單-1-1',
'pid'=>'4',
'path'=>'0-2-4',
),
array(
'id'=>'7',
'name'=>'二級菜單-1-2',
'pid'=>'4',
'path'=>'0-2-4',
),
array(
'id'=>'8',
'name'=>'三級菜單',
'pid'=>'0',
'path'=>'0',
),
array(
'id'=>'9',
'name'=>'二級菜單-1-3',
'pid'=>'4',
'path'=>'0-2-4-6',
),
array(
'id'=>'10',
'name'=>'三級菜單-1',
'pid'=>'8',
'path'=>'0-8',
),
);
return $rows;
}
// 遞歸子級
public function findchild(&$arr,$id){
$childs=array();
foreach ($arr as $key => $value) {
if($value['pid']==$id){
$childs[]=$value;
}
}
return $childs;
}
// 查找當前級別的子級
public function build_tree($root_id){
$rows = $this->arr();
$childs=$this->findchild($rows,$root_id);
if(empty($childs)){
return null;
}
foreach ($childs as $key => $value) {
$rescurTree=$this->build_tree($value['id']);
if(null != $rescurTree){
$childs[$key]['childs']=$rescurTree;
}
}
return $childs;
}
public function getDg(){
$dg = $this->build_tree("0");
return json($dg);
}