更新
我最近answered 这个问题在关于排序多维数组的“权威”主题中以一种更有能力的方式提出。您可以放心地跳过阅读此答案的其余部分,并直接点击链接以获得更强大的解决方案。
原答案
函数uasort 允许您定义自己的比较函数。只需将您想要的所有标准都放入其中。
例如,先按生日再按姓名排序:
function comparer($first, $second) {
// First see if birthdays differ
if ($first['birthday'] < $second['birthday']) {
return -1;
}
else if ($first['birthday'] > $second['birthday']) {
return 1;
}
// OK, birthdays are equal. What else?
if ($first['name'] < $second['name']) {
return -1;
}
else if ($first['name'] > $second['name']) {
return 1;
}
// No more sort criteria. The two elements are equal.
return 0;
}
我忽略了这样一个事实,即在您的示例中,生日不是可以通过使用运算符< 进行简单比较来排序的格式。在实践中,您会先将它们转换为可简单比较的格式。
更新:如果你认为维护一堆这些多标准比较器可能会很快变得丑陋,你会发现我同意。但是这个问题可以像计算机科学中的任何其他问题一样解决:只需添加另一个抽象级别。
我将假设下一个示例使用 PHP 5.3,以便使用方便的匿名函数语法。但原则上,您可以对 create_function 执行相同的操作。
function make_comparer() {
$criteriaNames = func_get_args();
$comparer = function($first, $second) use ($criteriaNames) {
// Do we have anything to compare?
while(!empty($criteriaNames)) {
// What will we compare now?
$criterion = array_shift($criteriaNames);
// Do the actual comparison
if ($first[$criterion] < $second[$criterion]) {
return -1;
}
else if ($first[$criterion] > $second[$criterion]) {
return 1;
}
}
// Nothing more to compare with, so $first == $second
return 0;
};
return $comparer;
}
你可以这样做:
uasort($myArray, make_comparer('birthday', 'name'));
这个例子可能太聪明了;一般来说,我不喜欢使用不接受名称参数的函数。但在这种情况下,使用场景是过于聪明的一个非常有力的论据。