场景:在二维数组中,想根据某一列对数组进行排序
代码
/**
* 二维数组排序
* @param array $arr 要排序的数组
* @param string $col_key $arr 根据哪一列
* @param string $sort_type desc:降序 asc:升序
* @param string $sort_key_type 排序类型 SORT_NUMERIC|SORT_STRING
*/
function array_multi_sort($arr , $col_key , $sort_type = 'desc' , $sort_key_type = SORT_NUMERIC){
$type = SORT_DESC;
if($sort_type == 'asc'){
$type = SORT_ASC;
}
$col_arr = array_column($arr, $col_key);
array_multisort($col_arr,$sort_key_type, $type ,$arr );
// array_multisort($col1_arr,$sort_key_type, $type ,$col2_arr, $sort_key_type, $type ,$arr );
return $arr;
}
输出
$arr = [
[
'id' => 1,
'name' => '张1',
'age' => 28
],
[
'id' => 3,
'name' => '张3',
'age' => 21
],
[
'id' => 2,
'name' => '张2',
'age' => 23
],
[
'id' => 8,
'name' => '张8',
'age' => 13
],
[
'id' => 3,
'name' => '张4',
'age' => 17,
],
];
echo "<pre />";
var_dump(array_multi_sort($arr,'age','asc'));
// array(5) {
// [0]=>
// array(3) {
// ["id"]=>
// int(8)
// ["name"]=>
// string(4) "张8"
// ["age"]=>
// int(13)
// }
// [1]=>
// array(3) {
// ["id"]=>
// int(3)
// ["name"]=>
// string(4) "张4"
// ["age"]=>
// int(17)
// }
// [2]=>
// array(3) {
// ["id"]=>
// int(3)
// ["name"]=>
// string(4) "张3"
// ["age"]=>
// int(21)
// }
// [3]=>
// array(3) {
// ["id"]=>
// int(2)
// ["name"]=>
// string(4) "张2"
// ["age"]=>
// int(23)
// }
// [4]=>
// array(3) {
// ["id"]=>
// int(1)
// ["name"]=>
// string(4) "张1"
// ["age"]=>
// int(28)
// }
//}