从多个阵列创建排名列表

时间:2013-07-28 13:57:48

标签: php arrays

我有3个数组返回来自3个不同搜索引擎的网址,标题,片段和分数,数组中元素的分数从100开始,第二个99分等等,我正在尝试将所有3个结合起来成一个阵列。如果网址与不同的数组匹配,我想将分数加在一起,然后删除重复的网址。如果url之间没有匹配,那么我只想将此元素放入组合数组中。  最终的组合列表应该包含所有不同的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

foreach($jsonObj->d->results as $value)
    {   $i = 0;

        $bingArray[]['Url'] = ($value->{'Url'});            
        $bingArray[]['Title'] = ($value->{'Title'});
        $bingArray[]['Description'] = ($value->{'Description'});
        $bingArray[]['score'] = $score--;
        $i++;
    }

任何帮助都会很棒,提前谢谢

1 个答案:

答案 0 :(得分:0)

此解决方案取决于几项工作。首先,urlscore密钥必须相同,即所有小写,没有"链接。"其次,URL必须标准化,因为它们充当数组的键。如果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);