/**
* 递归根据特定key对数组排序
* @param $data
* @param string $orderKey
* @param string $sonKey
* @param int $orderBy
* @return mixed
*/
function recursion_orderby($data, $orderKey = 'order', $sonKey = 'children', $orderBy = SORT_ASC)
{
$func = function ($value) use ($sonKey, $orderKey, $orderBy) {
if (isset($value[$sonKey]) is_array($value[$sonKey])) {
$value[$sonKey] = recursion_orderby($value[$sonKey], $orderKey, $sonKey, $orderBy);
}
return $value;
};
return array_orderby(array_map($func, $data), $orderKey, $orderBy);
}
$a = [
[
'order' => 0,
],
[
'order' => -1,
'children' => [
[
'order' => 0,
],
[
'order' => -2,
'children' => [
['order' => 0],
['order' => -1],
['order' => 1],
],
],
],
],
[
'order' => 2,
],
];
var_dump(recursion_orderby($a));
/**
* 输出:
array(3) {
[0] =>
array(2) {
'order' =>
int(-1)
'children' =>
array(2) {
[0] =>
array(2) {
'order' =>
int(-2)
'children' =>
array(3) {
[0] =>
array(1) {
'order' =>
int(-1)
}
[1] =>
array(1) {
'order' =>
int(0)
}
[2] =>
array(1) {
'order' =>
int(1)
}
}
}
[1] =>
array(1) {
'order' =>
int(0)
}
}
}
[1] =>
array(1) {
'order' =>
int(0)
}
[2] =>
array(1) {
'order' =>
int(2)
}
}
*/
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP数据结构与算法教程》、《php程序设计算法总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP常用遍历算法与技巧总结》及《PHP数学运算技巧总结》