有以下多维数组:
$items = [
[
"name" =>"首页",
"desc" =>"",
"route" =>"home",
"sort" =>9,
"menus" =>[]
],
[
"name" =>"管理员",
"desc" =>"",
"route" =>"admin",
"sort" =>4,
"menus" =>[
[
"name" =>"用户管理",
"desc" =>"",
"route" =>"admin/user",
"sort" =>6,
"menus" =>[
[
"name" =>"用 户列表",
"desc" =>"",
"route" =>"admin/user/list",
"sort" =>3,
"menus" =>[]
],
[
"name" =>"创建用户",
"desc" =>"",
"route" =>"admin/user/create",
"sort" =>2,
"menus" =>[]
]
]
],
[
"name" =>"权限管理",
"desc" =>"",
"route" =>"admin/rule",
"sort" =>8,
"menus" =>[
[
"name" =>"权限列表",
"desc" =>"",
"route" =>"admin/rule/list",
"sort" =>1,
"menus" =>[]
]
]
],
[
"name" =>"分组管理",
"desc" =>"",
"route" =>"admin/group",
"sort" =>5,
"menus" =>[
[
"name" =>"分组列表",
"desc" =>"",
"route" =>"admin/gr oup/list",
"sort" =>7,
"menus" =>[]
],
[
"name" =>"分组-权限",
"desc" =>"",
"route" =>"admin/group/rule",
"sort" =>11,
"menus" =>[
[
"name" =>"分组-权限:列表",
"desc" =>"",
"route" =>"admin/group/rule/list",
"sort" =>10,
"menus" =>[]
]
]
]
]
]
]
]
]
要求按sort对该多维数组进行排序
算法函数:递归、冒泡排序
function arrSort(array &$items, $sortField, $subField = null)
{
if (!($len = count($items))) return;
if (!is_null($subField)) {
foreach ($items as &$item) {
arrSort($item[$subField], $sortField, $subField);
}
}
for ($i = 1; $i < $len; $i++) {
for ($j = 0; $j < $len - $i; $j++) {
if ($items[$j][$sortField] > $items[$j + 1][$sortField]) {
$tmp = $items[$j];
$items[$j] = $items[$j + 1];
$items[$j + 1] = $tmp;
}
}
}
}
//排序
arrSort($items, 'sort', 'menus');
排序结果:
[
[
"name" =>"管理员",
"desc" =>"",
"route" =>"admin",
"sort" =>4,
"menus" =>[
[
"name" =>"分组管理",
"desc" =>"",
"route" =>"admin/group",
"sort" =>5,
"menus" =>[
[
"name" =>"分组列表",
"desc" =>"",
"route" =>"admin/group/list",
"sort" =>7,
"menus " =>[]
],
[
"name" =>"分组-权限",
"desc" =>"",
"route" =>"admin/group/rule",
"sort" =>11,
"menus" =>[
[
"name" =>"分组-权限:列表",
"desc" =>"",
"route" =>"admin/group/rule/list",
"sort" =>10,
"menus" =>[]
]
]
]
]
],
[
"name" =>"用户管理",
"desc" =>" ",
"route" =>"admin/user",
"sort" =>6,
"menus" =>[
[
"name" =>"创建用户",
"desc" =>"",
"route" =>"admin/user/create",
"sort" =>2,
"menus" =>[]
],
[
"name" =>"用户列表",
"desc" =>"",
"route" =>"admin/user/list",
"sort" =>3,
"menus" =>[]
]
]
],
[
"name " =>"权限管理",
"desc" =>"",
"route" =>"admin/rule",
"sort" =>8,
"menus" =>[
[
"name" =>"权限列表",
"desc" =>"",
"route" =>"admin/rule/list",
"sort" =>1,
"menus" =>[]
]
]
]
]
],
[
"name" =>"首页",
"desc" =>"",
"route" =>"home",
"sort" =>9,
"menus" =>[]
]
]