/**
* @param array $arr
* @param array $keys
* @param array $order
* @return bool|mixed
*/
function sortArrayMulti(array &$arr, array $keys, array $order)
{
//校验参数
if ( count($keys) == ($times = count($order)) ) {
for ( $i = 0, $j = 0; $j < $times; $i += 2, $j++ ) {
foreach ( $arr as $k => $v ) {
//原数组是否存在该字段
if ( isset($v[$keys[$j]]) ) {
$params[$i][] = $v[$keys[$j]]; //TODO 中文排序支持
} else {
return false;
}
}
if ( strtoupper($order[$j]) == 'ASC' ) {
$params[$i + 1] = SORT_ASC;
} else {
$params[$i + 1] = SORT_DESC;
}
}
$params[] = &$arr;
return call_user_func_array('array_multisort', $params);
} else {
return false;
}
}
$data = [
['name' => 1, 'score' => 2.2],
['name' => 2, 'score' => 3.3],
['name' => 4, 'score' => 2.5],
['name' => 1, 'score' => 1.1],
['name' => 0, 'score' => 4],
];
//调用方法
sort_array_multi($data, ['name', 'score'], ['asc', 'desc']);
网友评论