最近遇到这样一个问题:
function listToTree($arr){
$tree = [];
$data = [];
//数组降维 增加pid
foreach($arr as $k => $v){
$level = count($v) / 2 + 1;
for($i = 1; $i <= $level; $i++){
if(isset($v[$i.'_class'])){
$item[$v[$i.'_id']]['value'] = $v[$i.'_id'];
$item[$v[$i.'_id']]['label'] = $v[$i.'_class'];
$item[$v[$i.'_id']]['pid'] = isset($v[($i - 1).'_id']) ? $v[($i - 1).'_id'] : 0;
$item[$v[$i.'_id']]['children'] = [];
$data[$v[$i.'_id']] = $item[$v[$i.'_id']];
}
}
}
//ksort($data);
foreach($data as $key => $item){
$parentId = $item['pid'];
unset($data[$key]['pid']);
if(0 == $parentId){
$tree[] = &$data[$key];
}else{
if(isset($data[$parentId])){
$parent = &$data[$parentId];
$parent['children'][] = &$data[$key];
}
}
}
return $tree;
}
数组:$arr = [
[
'1_class' => '工具',
'2_class' => '备忘录',
'1_id' => 1,
'2_id' => 2,
],
[
'1_class' => '教育',
'2_class' => '学历教育',
'3_class' => '中等',
'1_id' => 3,
'2_id' => 4,
'3_id' => 6,
],
[
'1_class' => '教育',
'2_class' => '学历教育',
'3_class' => '高等',
'1_id' => 3,
'2_id' => 4,
'3_id' => 5,
],
[
'1_class' => '教育',
'2_class' => '成人教育',
'1_id' => 3,
'2_id' => 7,
],
];
结果:[{
"value": 1,
"label": "工具",
"children": [{
"value": 2,
"label": "备忘录",
"children": []
}]
}, {
"value": 3,
"label": "教育",
"children": [{
"value": 4,
"label": "学历教育",
"children": [{
"value": 6,
"label": "中等",
"children": []
}, {
"value": 5,
"label": "高等",
"children": []
}]
}, {
"value": 7,
"label": "成人教育",
"children": []
}]
}]