2017-06-01 61 views
1

我需要使用以下邏輯對以下數組進行排序:如果'分數'是相同的,我想使用'時間'進行比較。陣列是如下:使用usort和飛船操作符正確排序多維數組

$user_scores = [ 82 => [ 'score' => 1, 'time' => 6.442 ], 
       34 => [ 'score' => 1, 'time' => 5.646 ], 
       66 => [ 'score' => 3, 'time' => 1.554 ] 
       ] 

上述陣列中的「鍵」是「user_ids」,這我需要的排序後的數組中保存。我最好的嘗試至今如下 -

$result = usort($user_scores, function ($a, $b) { 
    if ($a['score'] == $b['score']) { 
     return $a['time'] == $b['time']; 
     } 
    return $a['score'] <=> $b['score']; 
}); 

很顯然,這是行不通的,而我得到0,1,2,而不是user_ids(82,34換成$ user_scores陣列的所有密鑰和66)。分類也不起作用。

對於上述陣列,我期望的輸出將是$ user_scores數組:

$user_scores = [ 34 => [ 'score' => 1, 'time' => 5.646 ], 
       82 => [ 'score' => 1, 'time' => 6.442 ], 
       66 => [ 'score' => 3, 'time' => 1.554 ] 
       ] 

真的很感激,如果你能告訴我如何使使用飛船操作這項工作(如果這是有道理的)。感謝您的時間,我期待您的回覆。

--- --- UPDATE

所需的排序邏輯是這樣的:

  1. 分數越高,更高的將是排名。
  2. 時間越長,排名越低。

這基本上是排序測驗的結果。時間最少的頂尖得分手將位居榜首;而分數較低和時間較長的人則處於最底層。

回答

1

要保存密鑰,您只需要使用uasort()
我在你回來的time比較中加了一個太空船。
我改變了你回來的訂單score的比較。
$result在你的代碼中只會返回true/false這樣對你沒用。 sort()'ing函數不被分配給一個變量;它們直接影響輸入數組。

方法:

$user_scores = [ 82 => [ 'score' => 1, 'time' => 6.442 ], 
       34 => [ 'score' => 1, 'time' => 5.646 ], 
       66 => [ 'score' => 3, 'time' => 1.554 ], 
       7 => [ 'score' => 2, 'time' => 4.442 ], 
       99 => [ 'score' => 4, 'time' => 3.646 ], 
       55 => [ 'score' => 1, 'time' => 2.554 ] 
       ]; 

uasort($user_scores,function($a,$b){ 
    if($a['score'] == $b['score']){ 
     return $a['time'] <=> $b['time']; 
    } 
    return $b['score'] <=> $a['score']; 
}); 
var_export($user_scores); 

輸出:

array (
    99 => 
    array (
    'score' => 4, 
    'time' => 3.646, 
), 
    66 => 
    array (
    'score' => 3, 
    'time' => 1.554, 
), 
    7 => 
    array (
    'score' => 2, 
    'time' => 4.442, 
), 
    55 => 
    array (
    'score' => 1, 
    'time' => 2.554, 
), 
    34 => 
    array (
    'score' => 1, 
    'time' => 5.646, 
), 
    82 => 
    array (
    'score' => 1, 
    'time' => 6.442, 
), 
) 
+0

時間關鍵是在輸出變化意味着時間= 5.646至5.64599999999999990762944435118697583675384521484375 –

+0

確保檢查在這裏https://eval.in/809606 –

+0

但如果你使用print_r()然後https://eval.in/809610它將ok –