- 数据结构:
$item=[
[
'id'=>1,
'parent'=>0,
'name'=>'A'
],
[
'id'=>2,
'parent'=>0,
'name'=>'B'
],
[
'id'=>3,
'parent'=>2,
'name'=>'B-1'
],
[
'id'=>4,
'parent'=>3,
'name'=>'B-1-1'
],
[
'id'=>5,
'parent'=>1,
'name'=>'A-1'
]
];
2.获取无限分类方法:
function getTree($categories,$parent=0){
$new_category=[];
foreach ($categories as $category){
if ($category['parent']==$parent) {
$category['child']=call_user_func_array(__FUNCTION__,[$categories,$category['id']]);
$new_category[]=$category;
}
}
return $new_category;
}
3.运行结果
array:2 [▼
0 => array:4 [▼
"id" => 1
"parent" => 0
"name" => "A"
"child" => array:1 [▼
0 => array:4 [▼
"id" => 5
"parent" => 1
"name" => "A-1"
"child" => []
]
]
]
1 => array:4 [▼
"id" => 2
"parent" => 0
"name" => "B"
"child" => array:1 [▼
0 => array:4 [▼
"id" => 3
"parent" => 2
"name" => "B-1"
"child" => array:1 [▼
0 => array:4 [▼
"id" => 4
"parent" => 3
"name" => "B-1-1"
"child" => []
]
]
]
]
]
]