2012-05-03 72 views
1

我有陣列的N個(例如3個陣列。):PHP排序多陣列具有多優先

$arr1 = array(0 => array('id' => 34, 'score' => 440), 
      1 => array('id' => 32, 'score' => 140), 
      2 => array('id' => 22, 'score' => 121), 
      3 => array('id' => 99, 'score' => 532) 
    ); 

$arr2 = array(0 => array('id' => 32, 'score' => 213), 
      1 => array('id' => 34, 'score' => 354), 
      2 => array('id' => 22, 'score' => 674) 
    ); 

$arr3 = array(0 => array('id' => 34, 'score' => 10), 
      1 => array('id' => 22, 'score' => 449), 
      2 => array('id' => 99, 'score' => 586), 
      3 => array('id' => 32, 'score' => 113), 
      4 => array('id' => 16, 'score' => 777) 

    ); 

我想取決於(ID)和(分數),但我這些(N)陣列排序希望優先考慮所有數組中的重複id事件,然後優先考慮最大分數,結果將是(1)根據這些排序規則,過濾唯一數組,其中包含唯一標識符。

我試圖做到這一點使用php usort函數來傳遞比較函數,但我沒有做到這一工作。

+1

這個信息從數據庫中來嗎?因爲如果是這樣的話,數據庫可以更輕鬆地處理這個問題。 –

+0

是的,這個信息來自數據庫,因爲我建立搜索索引表並想對結果進行排序 – semsem

回答

1

如果數據的來源來自mysql數據庫,則可以使用簡單的sql查詢輕鬆檢索此自定義排序。

但是,如果我們必須與陣列直接合作那麼這應該工作太:(對不起,髒編碼和流動性差)

$all_arrays = array_merge($arr1, $arr2, $arr3); // merge all arrays into one 
$items = $ascores = $scores = $occurs = $sorted_ids = array(); 
foreach($all_arrays as $elem) { 
    if(isset($occurs[ $elem['id'] ])) { $occurs[ $elem['id'] ]++; } else { $occurs[ $elem['id'] ] = 1; } 
    if(! isset($ascores[ $elem['id'] ]) || $elem['score'] > max($ascores[ $elem['id'] ])) { 
     $ascores[ $elem['id'] ][] = $elem['score']; 
     $scores[ $elem['id'] ] = $elem['score']; 
    } 
    $items[ $elem['id'] ] = array('id'=>$elem['id'], 'maxs'=>$scores[ $elem['id'] ], 'occs'=>$occurs[ $elem['id'] ]); 
} 

array_multisort($occurs, SORT_DESC, $scores, SORT_DESC, $items); 
/// print_r($items); // $items holds unique sorted data. outputs: Array ([0] => Array ([id] => 22 [maxs] => 674 [occs] => 3) [1] => Array ([id] => 34 [maxs] => 440 [occs] => 3) [2] => Array ([id] => 32 [maxs] => 213 [occs] => 3) [3] => Array ([id] => 99 [maxs] => 586 [occs] => 2) [4] => Array ([id] => 16 [maxs] => 777 [occs] => 1)) 

foreach($items as $item) $sorted_ids[] = $item['id']; 
/// print_r($sorted_ids); // $sorted_ids holds your desired ids list. outputs: Array ([0] => 22 [1] => 34 [2] => 32 [3] => 99 [4] => 16) 
+1

精彩的代碼給出了所需的結果 謝謝 請你可以舉個例子來做這個使用數據庫嗎? – semsem