我知道还有其他一些关于使用多个条件进行排序的主题,但是它们不能解决我的问题。假设我有这个数组:
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
)
)
如您所见,该数组未正确排序...有人知道我在做什么错吗?非常感谢!
您的功能应如下所示:
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
)
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句