2009-12-21 74 views
0

我已經搜索了這個,但似乎無法找到確切的答案。我想使用array_multisort基於3個數組中的數值同時對3個數組進行排序。基本上我想要製作一個類似於NFL/NHL排名等級的「積分榜」表。我有3個數組,tempIDs(字符串),tempWins(數字),tempWinPercentage(數字)。我需要首先根據勝利同時排序所有3個,然後如果有平局,贏得比例。array_multisort排序幾個陣列

我似乎無法讓array_multisort與多於兩個數組一起工作,所以也許我誤解了術語,當他們說它可以與「幾個」數組一起工作時。謝謝!

回答

5

你應該有一個數據數組是這樣的:

$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')

您的回調方法應該先比較tempWins這個數組排序,如果相等,比較tempWinPercentages:

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; 
} 

(這可以縮短)

+0

你會得到數組排序的,謝謝!這工作完美。 – mjdth 2009-12-21 02:41:16

1

我似乎無法在array_multisort得到 工作,不僅僅是2個數組,所以 也許我誤解了 術語時,他們說,它可以用 「幾個」陣列工作。謝謝!

我認爲他們的意思是它可以用於排序兩個以上的數組,但其他數組將基於第一個排序。

在例子中,執行此代碼

$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);