使用PHP多个条件排序数组 [英] Sort array using multiple criteria in PHP
问题描述
我知道大约有多个标准分拣一些其他的话题,但他们没有解决我的问题。
比方说,我有这样的数组:
I know there are some other topics about sorting with multiple criteria, but they don't fix my problem. Let's say I have this array:
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
)
)
我要对它进行排序,把一个在顶部的最高得分。在同样的比分,我想一个在顶部的最低数量残局。
排序mechanisme应该前列用户1,用户2话,那么4,然后用户3。
I want to sort it, putting the one with the HIGHEST score on top. On same score, I want the one with the LOWEST endgame number on top. The sorting mechanisme should rank user1 on top, then user2, then 4 and then user3.
我用这个排序mechanisme:
I use this sorting mechanisme:
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
)
)
正如你所看到的,阵列没有适当的排序...任何人都知道我做错了什么?非常感谢!
As you can see, the array isn't sorted properly... Anyone knows what I'm doing wrong? Thanks a lot!
推荐答案
您函数应该是这样的:
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;
}
试试吧。它会给你带来这样的:
Try it out. It will give you result like this:
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
)
)
这篇关于使用PHP多个条件排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!