【问题标题】:Creating a ranked list from multiple arrays从多个数组创建排名列表
【发布时间】:2013-07-29 03:49:28
【问题描述】:

我有 3 个数组,它们从 3 个不同的搜索引擎返回一个 url、title、sn-p 和分数,数组中元素的分数从 100 开始,第二个 99 等等,我正在尝试组合所有 3 到一个数组中。如果 url 从不同的数组中匹配,我想将分数相加,然后删除重复的 url。如果 url 之间不匹配,那么我只想将此元素放入组合数组中。 最终的组合列表应包含所有不同的 url 及其分数、标题和 sn-p,这是我的数组结构

谷歌数组

$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++;
    }

任何帮助都会很棒,在此先感谢

【问题讨论】:

  • $i 在 bingArray 中没用。另外,为什么在不同的数组中有不同的名称:链接、网址、网址?这会使解决问题变得复杂。
  • link、url 和 Url 是不同搜索引擎放入数组的名称,但是是的,我可以更改数组中的分配,但这是我最少的问题
  • 是的,如果所有数组对相似的数据有相同的键名来统一解决方案会更好

标签: php arrays


【解决方案1】:

此解决方案取决于几项工作。首先,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;
}

如果您不想保留 URL 作为键,请添加以下行:

$combined = array_values($combined);

如果要按分数对数组进行排序,可以使用usort

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

【讨论】:

    猜你喜欢
    • 2014-03-10
    • 2020-11-24
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    相关资源
    最近更新 更多