@
azhi ~~~
/**
* 数组生成树形
* @
param array $list 二维数组,内部有 pid,name,id 字段
* @
return array 树形数组
* @
throws Exception 报错
*/
function listToTree($list)
{
$data = [];
$tree = [];
$ids = array_unique(array_column($list, 'id'));
foreach ($list as $item) {
if (!in_array($item['pid'], $ids)) {
$data[$item['pid']][] = $item;
} else {
$tree[] = $item;
}
}
/**
* 闭包递归函数
* @
param int $pid 父 id
* @
param mixed $callback 递归函数,默认闯入本函数
* @
param int $count 当前递归层
* @
param int $max 最大递归层
* @
return array
*/
$treeFun = function ($pid, $callback, $count = 1, $max = 10) use ($data) {
try {
$sub = $data[$pid];
} catch (\Exception $e) {
return [];
}
if (!empty($sub) && $count <= $max) {
$count++;
foreach ($sub as $it) {
$sub['sub'] = $callback($it, $callback, $count);
}
}
return $sub;
};
if (empty($tree)) {
throw new Exception('未找到根节点');
} else {
foreach ($tree as &$item) {
$item['sub'] = $tree($item['id'], $treeFun);
}
}
return $tree;
}
~~~