数据表:
代码:
public static function infiniteSort(array $data, $pid = 0)
{
// 返回的结果
$arr = [];
foreach ($data as $val) {
// 给定的PID是当前记录的上级ID
if ($pid == $val['pid']) {
// 递归
$val['sub'] = self::infiniteSort($data, $val['id']);
$arr[] = $val;
}
}
return $arr;
}
封装一个类将这个方法代码放进去:
调用:
未处理前数据:
Array
(
[0] => Array
(
[id] => 1
[power_name] => 产品管理
[route] => product_management
[pid] => 0
)
[1] => Array
(
[id] => 2
[power_name] => 应用管理
[route] => application_management
[pid] => 0
)
[2] => Array
(
[id] => 3
[power_name] => 设备管理
[route] => device_management
[pid] => 0
)
[3] => Array
(
[id] => 4
[power_name] => 产品列表
[route] =>
[pid] => 1
)
[4] => Array
(
[id] => 5
[power_name] => 产品删除
[route] =>
[pid] => 1
)
[5] => Array
(
[id] => 6
[power_name] => 应用列表
[route] =>
[pid] => 2
)
[6] => Array
(
[id] => 7
[power_name] => 应用删除
[route] =>
[pid] => 2
)
[7] => Array
(
[id] => 8
[power_name] => 设备列表
[route] =>
[pid] => 3
)
[8] => Array
(
[id] => 9
[power_name] => 设备删除
[route] =>
[pid] => 3
)
)
处理后数据:
Array
(
[0] => Array
(
[id] => 1
[power_name] => 产品管理
[route] => product_management
[pid] => 0
[sub] => Array
(
[0] => Array
(
[id] => 4
[power_name] => 产品列表
[route] =>
[pid] => 1
[sub] => Array
(
)
)
[1] => Array
(
[id] => 5
[power_name] => 产品删除
[route] =>
[pid] => 1
[sub] => Array
(
)
)
)
)
[1] => Array
(
[id] => 2
[power_name] => 应用管理
[route] => application_management
[pid] => 0
[sub] => Array
(
[0] => Array
(
[id] => 6
[power_name] => 应用列表
[route] =>
[pid] => 2
[sub] => Array
(
)
)
[1] => Array
(
[id] => 7
[power_name] => 应用删除
[route] =>
[pid] => 2
[sub] => Array
(
)
)
)
)
[2] => Array
(
[id] => 3
[power_name] => 设备管理
[route] => device_management
[pid] => 0
[sub] => Array
(
[0] => Array
(
[id] => 8
[power_name] => 设备列表
[route] =>
[pid] => 3
[sub] => Array
(
)
)
[1] => Array
(
[id] => 9
[power_name] => 设备删除
[route] =>
[pid] => 3
[sub] => Array
(
)
)
)
)
)