代码之家  ›  专栏  ›  技术社区  ›  mjdth

array\u multisort可对多个数组进行排序

php
  •  0
  • mjdth  · 技术社区  · 16 年前

    我已经找过了,但似乎找不到确切的答案。我想使用array_multisort根据其中3个数组中的数值同时对3个数组进行排序。基本上,我想制作一个类似于NFL/NHL排名等的“排名”表。我有3个数组,tempID(字符串)、tempWins(数字)、tempWinPercentage(数字)。我需要所有3个被排序在同一时间的基础上首先赢,然后如果有一个平局,赢的百分比。

    2 回复  |  直到 16 年前
        1
  •  5
  •   Joel L    16 年前

    您应该有这样一个数据数组:

    $data = array(
        0 => array(
            'tempIDs' => 'something',
            'tempWins' => 10,
            'tempWinPercentage' => 50,
        ),
        1 => array(
            'tempIDs' => 'something else',
            'tempWins' => 10,
            'tempWinPercentage' => 60,
        ),
        3 => array(
            'tempIDs' => 'something more',
            'tempWins' => 20,
            'tempWinPercentage' => 50,
        ),
    );
    

    然后使用 usort($data, 'my_sort_cb')

    function my_sort_cb($a, $b) {
        if ($a['tempWins'] > $b['tempWins']) return 1;
        if ($a['tempWins'] < $b['tempWins']) return -1;
    
        if ($a['tempWinPercentage'] > $b['tempWinPercentage']) return 1;
        if ($a['tempWinPercentage'] < $b['tempWinPercentage']) return -1;
        return 0;
    }
    

    (这可以缩短)

        2
  •  1
  •   avpaderno    16 年前

    我似乎无法将数组\u multisort设置为 也许我误会了 术语当他们说它可以 使用“多个”数组。非常感谢。

    我认为这意味着它可以用于排序两个以上的数组,但其他数组将根据第一个数组进行排序。

    在示例中,执行此代码

    $a1 = array(12, 23, 34, 45, 45, 34);
    $a2 = array(234, 56, 243, 456, 34, 346);
    $a3 = array(654, 56, 8, 12, 56, 90);
    
    array_multisort($a1, $a2, $a3);
    

    您将对数组进行排序,就像将

    $a1 = array(12, 23, 34, 34, 45, 45);
    $a3 = array(654, 56, 8, 90, 56, 12);
    
    推荐文章