【问题标题】:Sort array using multiple criteria in PHP [duplicate]在PHP中使用多个条件对数组进行排序[重复]
【发布时间】:2023-03-15 23:02:01
【问题描述】:

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

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
        )

)

如您所见,数组未正确排序...有人知道我做错了什么吗?非常感谢!

【问题讨论】:

  • $a['endgame'] == 'y'...!?你的价值观中没有“y”。
  • 我明白了...我在stackoverflow.com/questions/3606156/… 上找到了这种排序机制,因为头部值为“y”或“n”,所以在那里有意义。我的特定问题有一个简单的解决方法吗?我只是无法理解这种带有多个标准的排序......即使在阅读了有关此的手册和其他线程之后......
  • 将此作为规范解释的副本关闭。请阅读它,它应该解释排序的工作原理并使您能够修复您的代码。

标签: php arrays sorting multidimensional-array


【解决方案1】:

你的函数应该是这样的:

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
    )

)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    相关资源
    最近更新 更多