2013-07-28 194 views
0

我有3個數組,從3個不同的搜索引擎返回一個url,title,snippet和score,數組中的元素的分數從100開始,第二個99,等等試圖將所有3合併爲一個陣列。如果網址與不同陣列匹配,我想將分數添加到一起,然後刪除重複的網址。如果網址之間沒有匹配,那麼我只想把這個元素放到組合數組中。 最終的合併列表應包含其分數,標題和摘要的所有不同的URL上,這裏是我的陣列結構從多個陣列創建一個排名列表

googleArray

$x=0; 
$score=100; 
foreach ($js->items as $item) 
    { 
     $googleArray[$x]['link'] = ($item->{'link'}); 
     $googleArray[$x]['title'] = ($item->{'title'}); 
     $googleArray[$x]['snippet'] = ($item->{'snippet'}); 
     $googleArray[$x]['score'] = $score--; 
     $x++; 
    } 

blekkoArray

$score = 100; 
foreach ($js->RESULT as $item) 
{   
$blekkoArray[$i]['url'] = ($item->{'url'});   
$blekkoArray[$i]['title'] = ($item->{'url_title'}); 
$blekkoArray[$i]['snippet'] = ($item->{'snippet'}); 
$blekkoArray[$i]['score'] = $score--;  // assign the $score value here 
$i++; 

} 

bingArray

​​3210

任何幫助將是偉大的,在此先感謝

+0

$我在bingArray中沒用。另外爲什麼你在不同的數組中有不同的名稱:link,url,Url?這將使問題解決複雜化。 – user4035

+0

鏈接,網址和Url是不同搜索引擎放入數組的名稱,但是我可以更改數組中的賦值,但那是我的問題中最少的。 – user2622398

+0

是的,如果所有數組都具有相同用於統一解決方案的類似數據的關鍵名稱 – user4035

回答

0

該解決方案取決於幾件事情的工作。首先,urlscore鍵必須是相同的,即全部小寫,並且都不是「鏈接」。其次,這些URL必須標準化,因爲它們是數組的關鍵。如果這些網址存在任何差異,它們將在最終數組中顯示不止一次。

$merged = array_merge($googleArray, $blekkoArray); 
$merged = array_merge($merged, $bingArray); 
$combined = array(); 
foreach ($merged as $key => $value){ 
    $score = (isset($combined[$value['url']]['score'])) ? $value['score'] + $combined[$value['url']]['score'] : $value['score']; 
    $combined[$value['url']] = $value; 
    $combined[$value['url']]['score'] = $score; 
} 

如果你不想保持網址爲重點,加入這一行:如果你想按分數排序的數組

$combined = array_values($combined); 

,您可以使用usort

usort($combined, function ($a, $b){ 
    return $b['score'] - $a['score']; 
}); 
print_r($combined); 
+0

我剛更新了一些用於對數組進行排序的代碼。 –