2012-10-26 114 views
-3

可能重複:
PHP - Multiple uasort functions breaks sorting在PHP排序multidimesional陣列

我在PHP多維數組與3 columns.I需要通過 「awarded_units」 對它進行排序,如果兩個用戶有同樣的獲獎單位(tiebreaker),那麼選擇最少的單位將首先獲獎。

user_id awarded_units selected_units 

15  5    2 
22  5    1 
3  4    2 
4  4    5 
5  4    1 

正如你所看到的,我已經使用一些多維排序函數在頒發單元的基礎上對數組進行排序。現在,我需要解決tiebreaker的條件。由於user_id = 15和user_id = 22具有相同的awards_units,所以user_id 22必須在第一位。

正確的順序將是

user_id awarded_units selected_units 

22  5    1 
15  5    2 
5  4    1 
3  4    2 
4  4    5 

請告訴我該怎麼做this.Thanks

+1

在發佈之前,你看過數組排序嗎? http://php.net/manual/en/array.sorting.php – Peon

+2

PS:您是自己創建數組還是您從數據庫接收數據? – Peon

+0

特別參見['array_multisort']的PHP手冊中的[Example#3 Sorting database results](http://www.php.net/manual/en/function.array-multisort.php#example-4641) http://php.net/array_multisort)條目 - 如果你需要在PHP中解決這個問題。你還沒有發佈你的數組,所以這可能會略有不同。 – hakre

回答

1

您可以使用array_multisort

$cols = array(); 
foreach ($multiArray as $key => $value) 
{ 
    $cols['awarded_units'][$key] = $value['awarded_units']; 
    $cols['selected_units'][$key] = $value['selected_units']; 
} 
array_multisort($cols['awarded_units'], SORT_DESC, $cols['selected_units'], SORT_ASC, $multiArray); 
+0

第一個代碼示例更好。現在你改變了它。 – hakre

+0

以爲我看錯了這個問題,改回來了。 –

0

使用custom sort function with usort

usort($data, function($a, $b) { 
    if ($a['awarded_units'] == $b['awarded_units']) 
    { 
     return $b['selected_units'] - $a['selected_units']; 
    } 

    return $b['awarded_units'] - $a['awarded_units']; 
}); 

您也可以使用array_multisort,但我更喜歡使用usort - 更大的靈活性和更好的可讀性。

+0

但是另一方面'usort'很複雜,因爲你需要編寫比較代碼。經常發生錯誤 - 你的答案也是一個很好的例子。 – hakre