2012-07-16 61 views
0

當重複在URL找到我想:找到陣副本,添加到原來的,然後刪除

  1. 採取「分數」,並把它添加到原
  2. 採取「引擎」字符串其追加到原來的
  3. 然後刪除整個重複條目
array 
    0 => 
    array 
     'url' => string 'http://blahhotel.com/' 
     'score' => int 1 
     'engine' => string 'cheese' 
    1 => 
    array 
     'url' => string 'http://www.blahdvd.com/' 
     'score' => int 2 
     'engine' => string 'cheese' 
    2 => 
    array 
     'url' => string 'http://blahhotel.com/' 
     'score' => int 1 
     'engine' => string 'pie' 
    3 => 
    array 
     'url' => string 'http://dictionary.reference.com/browse/blah' 
     'score' => int 2 
     'engine' => string 'pie' 
    4 => 
    array 
     'url' => string 'http://dictionary.reference.com/browse/blah' 
     'score' => int 1 
     'engine' => string 'apples' 

它應該是這樣的結尾:

array 
    0 => 
    array 
     'url' => string 'http://blahhotel.com/' 
     'score' => int 2 
     'engine' => string 'cheese, pie' 
    1 => 
    array 
     'url' => string 'http://www.blahdvd.com/' 
     'score' => int 2 
     'engine' => string 'cheese' 
    3 => 
    array 
     'url' => string 'http://dictionary.reference.com/browse/blah' 
     'score' => int 3 
     'engine' => string 'pie, apples' 
+0

這是太辛苦了。 – hjpotter92 2012-07-16 17:48:39

+0

試圖什麼也沒做,失敗了? – alfasin 2012-07-16 17:53:03

+0

我一直在工作幾個小時。我將包含我的代碼片段,但它可能沒有幫助。我會隨着我的進展保持最新狀態。沒有必要是sn。。謝謝。 – flux 2012-07-16 17:55:40

回答

0

我相信這符合您的要求。

基於您提供的期望輸出,您似乎希望保留每個條目的數字索引。如果您實際上不需要保留這些數字,則可以刪除第二個foreach循環和有關$indices變量的行,然後僅返回$tmpList

function reduceEntries($entries) 
{ 
    $tmpList = array(); 
    $indices = array(); 

    foreach ($entries as $i => $entry) { 
     if (isset($tmpList[$entry['url']])) { 
      $tmpList[$entry['url']]['score'] += $entry['score']; 
      $tmpList[$entry['url']]['engine'] .= ', ' . $entry['engine']; 
     } else { 
      $tmpList[$entry['url']] = $entry; 
      $indices[$entry['url']] = $i; 
     } 
    } 

    // rebuild final array with indices 
    $finalList = array(); 
    foreach ($tmpList as $url => $entry) { 
     $finalList[$indices[$url]] = $entry; 
    } 

    return $finalList; 
} 

(這裏的a working example上鍵盤。)

相關問題