2

好的,这个很复杂......假设我有一个名为 $data 的数组

Array
(
    [9e5b0d6d-711c-4cd0-8697-634a5c640066] => Array
        (
            [player] => 9e5b0d6d-711c-4cd0-8697-634a5c640066
            [wins] => 1
            [loss] => 6
            [winsR] => 2
            [lossR] => 12
        )

    [a8f7fb4c-afab-4ec0-9202-b87fa2641110] => Array
        (
            [player] => a8f7fb4c-afab-4ec0-9202-b87fa2641110
            [wins] => 1
            [loss] => 6
            [winsR] => 2
            [lossR] => 12
        )

    [96ed2f95-08bd-42f8-bb57-9df09b66109d] => Array
        (
            [player] => 96ed2f95-08bd-42f8-bb57-9df09b66109d
            [wins] => 2
            [loss] => 5
            [winsR] => 4
            [lossR] => 10
        )

    [2a4e1a3e-cde4-4c9b-947e-67a4d333f0f4] => Array
        (
            [player] => 2a4e1a3e-cde4-4c9b-947e-67a4d333f0f4
            [wins] => 3
            [loss] => 4
            [winsR] => 6
            [lossR] => 8
        )

    [08c23d63-69a9-4147-b40f-64b241cfbb4f] => Array
        (
            [player] => 08c23d63-69a9-4147-b40f-64b241cfbb4f
            [wins] => 4
            [loss] => 3
            [winsR] => 8
            [lossR] => 6
        )

    [777e8f3e-caac-41fb-975e-a410e42f7114] => Array
        (
            [player] => 777e8f3e-caac-41fb-975e-a410e42f7114
            [wins] => 5
            [loss] => 2
            [winsR] => 11
            [lossR] => 4
        )

    [9cd5256f-6d3a-4bd5-aeed-b6904bcbf048] => Array
        (
            [player] => 9cd5256f-6d3a-4bd5-aeed-b6904bcbf048
            [wins] => 6
            [loss] => 1
            [winsR] => 12
            [lossR] => 3
        )

    [797c95df-c334-4328-a8eb-4ba5e690af4d] => Array
        (
            [player] => 797c95df-c334-4328-a8eb-4ba5e690af4d
            [wins] => 6
            [loss] => 1
            [winsR] => 12
            [lossR] => 2
        )
)

如您所见,我有一系列数据,每个元素都有自己的嵌套数组。我已经知道我可以使用单个嵌套值对数组进行排序

usort($data, create_function('$a, $b', 'return $b["wins"] - $a["wins"];')); 

然而,这还不够。

问题是,用上面的函数排序对我来说排序不够深。它所做的只是根据以下内容进行排序:

  • ['wins'] DESCENDING(最高的胜利排在第一位)

我想使用四个嵌套值进行排序。

  • ['wins'] DESCENDING(最高的胜利排在第一位)
  • ['loss'] ASCENDING(最低损失排序第二)
  • ['winsR'] DESCENDING(最高的 winsR 排在第三位)
  • ['lossR'] ASCENDING(最低 lossR 排在第四位)

我知道这很复杂,所以我来这里寻求帮助。最好和最有效的方法是什么?

4

1 回答 1

4

您正在寻找的是功能usort()

在那里,您可以提供自己的比较器来比较两个元素并应用您希望使用的规则。

您走在正确的轨道上,但您的比较器功能可以更加精细:

function compare_elements($l, $r) {
    if ($l['wins'] > $r['wins']) {
        return -1;
    } else if ($l['wins'] < $r['wins']) {
        return 1;
    }

    // Drop to second level; it will have exited by here
    // if the tie could be broken by the first rule.
    // You really could've put this in an else clause, but I
    // wanted to avoid excessive nesting.
    if ($l['loss'] > $r['loss']) {
        return 1;
    } else if ($l['loss'] < $r['loss']) {
        return -1;
    }

    // And so on until the 4th level    
}
于 2012-06-01T05:20:52.533 回答