这个解决方案适用于usort(),具有易于记忆的多维排序符号。使用了飞船操作符<=>,该操作符可从PHP 7获得。
usort($in,function($a,$b){
return $a['first'] <=> $b['first'] //first asc
?: $a['second'] <=> $b['second'] //second asc
?: $b['third'] <=> $a['third'] //third desc (a b swapped!)
//etc
;
});
例子:
$in = [
['firstname' => 'Anton', 'surname' => 'Gruber', 'birthdate' => '03.08.1967', 'rank' => 3],
['firstname' => 'Anna', 'surname' => 'Egger', 'birthdate' => '04.01.1960', 'rank' => 1],
['firstname' => 'Paul', 'surname' => 'Mueller', 'birthdate' => '15.10.1971', 'rank' => 2],
['firstname' => 'Marie', 'surname' => 'Schmidt ', 'birthdate' => '24.12.1963', 'rank' => 2],
['firstname' => 'Emma', 'surname' => 'Mueller', 'birthdate' => '23.11.1969', 'rank' => 2],
];
第一个任务:按等级asc,姓asc排序
usort($in,function($a,$b){
return $a['rank'] <=> $b['rank'] //first asc
?: $a['surname'] <=> $b['surname'] //second asc
;
});
第二项任务:按等级,姓,名排序
usort($in,function($a,$b){
return $b['rank'] <=> $a['rank'] //first desc
?: $a['surname'] <=> $b['surname'] //second asc
?: $a['firstname'] <=> $b['firstname'] //third asc
;
});
第三个任务:按级别desc,出生日期asc排序
日期不能用这种表示法排序。使用strtotime进行转换。
usort($in,function($a,$b){
return $b['rank'] <=> $a['rank'] //first desc
?: strtotime($a['birthdate']) <=> strtotime($b['birthdate']) //second asc
;
});