使用多个条件在PHP中对数组进行排序

10

我知道有一些其他关于使用多个条件进行排序的主题,但它们没有解决我的问题。 假设我有这个数组:

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
        )

)

我希望对它进行排序,将得分最高的放在顶部。在相同得分的情况下,我希望将结束游戏次数最低的放在顶部。 排序机制应该将用户1排在首位,然后是用户2,4号和用户3。

我使用以下排序机制:

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
        )

)

正如你所看到的,这个数组没有被正确地排序... 有人知道我做错了什么吗?非常感谢!


2
$a['endgame'] == 'y'...!? 你的值中没有'y'。 - deceze
我明白了...我在https://dev59.com/uVDTa4cB1Zd3GeqPGiXQ 上找到了这个排序机制,因为头部值是“y”或“n”,所以那里很有意义。对于我的问题,有没有简单的解决方法?我只是无法理解这种多条件排序...即使阅读了手册和其他相关主题... - binoculars
将此问题关闭为规范说明的重复。请阅读它,它应该解释了排序的工作原理,并使你能够修复你的代码。 - deceze
1个回答

18

你的函数应该像这样:

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
    )

)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接