/**
* 多维数组排序
*
* @Author Xven <QQ:270988107>
* @param [type] $args [description]
* @return [type] [description]
*/
function multi_dimension_sort(...$args){
$arr = array_shift($args); // 取到要排序的数组,剩下的为要排序的键和排序类型
$sort_arg = [];
foreach($args as $arg){
// 这里主要是为了得到排序的key对应的值
$sort = $arr;
if(is_string($arg)){
$arg = explode('.', $arg); // 我设定参数里面多维数组下的键,用‘.’连接下级的键,这里得到键,然后下面循环取得数组$arr里面该键对应的值
foreach($arg as $key){
$sort = array_column($sort, $key); // 每次循环$sort的维度就会减一
}
$sort_arg[] = $sort;
}else{
$sort_arg[] = $arg; // 排序方法SORT_ASC、SORT_DESC等
}
}
$sort_arg[] = &$arr; // 这个数组大致结构为:[$sort, SORT_ASC, $sort2, SORT_DESC,$arr]
call_user_func_array('array_multisort', $sort_arg); // 因为参数不确定数量,所以不能直接array_multisort($sort, SORT_ASC, $sort2, SORT_DESC,$arr),用call_user_func_array执行
return($arr);
}
方法如下
参数:第一个为要排序的数组,剩下是要排序的键(key),和排序方法,键的话因为要应对多维的情况,所以需要上下级连接,我这里采用"."连接,(multi_dimension_sort($arr, 'id', SORT_ASC, 'class.class_num', SORT_ASC, 'class.student.value', SORT_DESC)),参数可自行增减,具体看下面的例子
$arr = [
[
'id' => 2,
'name' => '学院2',
'class' => [
'class_num' => 2,
'student' => [
'student_id' => 5,
'value' => 20,
]
],
],[
'id' => 2,
'name' => '学院2',
'class' => [
'class_num' => 2,
'student' => [
'student_id' => 6,
'value' => 10,
]
],
],[
'id' => 2,
'name' => '学院2',
'class' => [
'class_num' => 3,
'student' => [
'student_id' => 4,
'value' => 30,
]
],
],[
'id' => 1,
'name' => '学院1',
'class' => [
'class_num' => 2,
'student' => [
'student_id' => 3,
'value' => 10,
]
],
],[
'id' => 1,
'name' => '学院1',
'class' => [
'class_num' => 2,
'student' => [
'student_id' => 4,
'value' => 5,
]
],
],[
'id' => 1,
'name' => '学院1',
'class' => [
'class_num' => 3,
'student' => [
'student_id' => 4,
'value' => 10,
]
],
],[
'id' => 2,
'name' => '学院2',
'class' => [
'class_num' => 2,
'student' => [
'student_id' => 7,
'value' => 20,
]
],
],[
'id' => 2,
'name' => '学院2',
'class' => [
'class_num' => 2,
'student' => [
'student_id' => 1,
'value' => 5,
]
],
]
];
dump(multi_dimension_sort($arr, 'id', SORT_ASC, 'class.class_num', SORT_ASC, 'class.student.value', SORT_DESC));