PHP二维数组按照键值排序
在开发过程中,我们常常需要对二维数组按照数组的某个键来排序,这里提供两个封装好的方法,可以放到公共函数模块里以后需要的时候直接调用即可。
/**
* 二维数组按照键值排序
* @param array $arr
* @param string $key
* @param int $sortType SORT_DESC|SORT_ASC
* @return mixed
*/
function sortByKey($arr, $key, $sortType)
{
array_multisort(array_column($arr, $key), $sortType, $arr);
return $arr;
}
$arr = [
['name' => 'itbsl', 'priority' => 23],
['name' => 'jack', 'priority' => 3],
['name' => 'rose', 'priority' => 12],
['name' => 'pick', 'priority' => 45],
['name' => 'binbin', 'priority' => 68],
['name' => 'didi', 'priority' => 56789],
['name' => 'mobike', 'priority' => 0],
];
//把数组arr按照priority的值降序(从大到小)排序
$result = sortByKey($arr, 'priority', SORT_DESC);
var_dump($result);
假设$arr数组中还有一个key为score的数据,我想按照priority降序,score升序排序,怎么办?array_multisort()依然支持
$arr = [
['name' => 'itbsl', 'priority' => 23, 'score' => 1],
['name' => 'jack', 'priority' => 3, 'score' => 8],
['name' => 'rose', 'priority' => 45, 'score' => 56],
['name' => 'pick', 'priority' => 45, 'score' => 1],
['name' => 'binbin', 'priority' => 68, 'score' => 3],
['name' => 'didi', 'priority' => 56789, 'score' => 1],
['name' => 'mobike', 'priority' => 0, 'score' => 23],
];
//按照priority降序、score升序排序
array_multisort(array_column($arr, 'priority'), SORT_DESC, array_column($arr, 'score'), SORT_ASC, $arr);
dump($arr);