我知道还有其他一些关于使用多个条件进行排序的主题,但它们并不能解决我的问题。 让我们说我有这个数组:
Array
(
[0] => Array
(
[uid] => 1
[score] => 9
[endgame] => 2
)
[1] => Array
(
[uid] => 2
[score] => 4
[endgame] => 1
)
[2] => Array
(
[uid] => 3
[score] => 4
[endgame] => 100
)
[3] => Array
(
[uid] => 4
[score] => 4
[endgame] => 70
)
)
我想对它进行排序,将最高分的那个放在最前面。在同样的分数上,我想要一个最低端赛号码的人。 排序机制应该将user1排在最前面,然后是user2,然后是4,然后是user3。
我使用这种排序机制:
function order_by_score_endgame($a, $b)
{
if ($a['score'] == $b['score'])
{
// score is the same, sort by endgame
if ($a['endgame'] == $b['endgame']) return 0;
return $a['endgame'] == 'y' ? -1 : 1;
}
// sort the higher score first:
return $a['score'] < $b['score'] ? 1 : -1;
}
usort($dummy, "order_by_score_endgame");
这给了我以下数组:
Array
(
[0] => Array
(
[uid] => 1
[score] => 9
[endgame] => 2
)
[1] => Array
(
[uid] => 3
[score] => 4
[endgame] => 100
)
[2] => Array
(
[uid] => 2
[score] => 4
[endgame] => 1
)
[3] => Array
(
[uid] => 4
[score] => 4
[endgame] => 70
)
)
正如您所看到的,阵列没有正确排序......任何人都知道我做错了什么?非常感谢!
答案 0 :(得分:10)
你的功能应该是这样的:
function order_by_score_endgame($a, $b){
if ($a['score'] == $b['score'])
{
// score is the same, sort by endgame
if ($a['endgame'] > $b['endgame']) return 1;
}
// sort the higher score first:
return $a['score'] < $b['score'] ? 1 : -1;
}
试一试。它会给你这样的结果:
Array
(
[0] => Array
(
[uid] => 1
[score] => 9
[endgame] => 2
)
[1] => Array
(
[uid] => 2
[score] => 4
[endgame] => 1
)
[2] => Array
(
[uid] => 4
[score] => 4
[endgame] => 70
)
[3] => Array
(
[uid] => 3
[score] => 4
[endgame] => 100
)
)