2016-02-10 19 views
2

我有此數組:基於2個鍵如何排序PHP數組,一個是升序,另一個是降序

$order_list = array (array ("tangible", 1, 8, 1, 19000), 
         array ("tangible", 6, 2, 10, NULL), 
         array ("tangible", 1, 17, 1, 28000)); 

,我有這樣的代碼對它進行排序:

usort($order_list, function ($a, $b) { 
    if ($a[1] == $b[1]) return 0; 
    return (int) $a[1] < (int) $b[1] ? -1 : 1; 
}); 

的問題是,它只按$order_list[$i][1]升序排列。它會產生這樣的結果:

array ("tangible", 1, 8, 1, 19000) 
array ("tangible", 1, 17, 1, 28000) 

雖然我需要$order_list[$i][2]也被排序,但降序。所以它會產生:

array ("tangible", 1, 17, 1, 28000) 
array ("tangible", 1, 8, 1, 19000) 
array ("tangible", 6, 2, 10, NULL) 

如何基於這樣的2鍵排序數組?以前感謝。

回答

3

在本compendium排序陣列已經解決,你可以只換$a$b,使其在時尚遞減:

usort($order_list, function ($a, $b) { 
    if(($c = $a[1] - $b[1]) !== 0) { 
     return $c; 
    } else { 
     return $b[2] - $a[2]; // descending 
    } 
}); 

Sample Output

+0

更好的解決方案比我的。 – bansi

+0

它像一個魅力,兄弟。非常感謝。對此,我真的非常感激。 –

+0

@bansi你的工作時間還有待延長 – Ghost

0

您應該更改排序算法以檢查第二列。你應該做下面的事情。代碼中的註釋。

usort($order_list, function ($a, $b) { 
    // if both columns are same return 0 
    if ((int) $a[1] == (int) $b[1] && (int) $a[2] == (int) $b[2]) return 0; 
    // if first column is equal sort on the second column 
    if ((int) $a[1] == (int) $b[1]){ 
     return (int) $a[2] > (int) $b[2] ? -1 : 1; 
    } 
    // else sort on the first column 
    return (int) $a[1] < (int) $b[1] ? -1 : 1; 
}); 
相關問題