在组合数组中添加额外元素

时间:2013-07-29 14:09:52

标签: php arrays

我帮助创建了一个组合数组,它接收来自相关数组的元素,数组中的网址和分数来自搜索引擎,当网址匹配时,分数在组合数组中加在一起,这里是代码

$combined = array(); 

foreach($bingArray as $key=>$value){ // for each bing item
if(isset($combined[$key]))
    $combined[$key] += $value['score']; // add the score if already exists in $combined
else
    $combined[$key] = $value['score']; // set initial score if new
}

然后为$ googleArray运行相同的代码,这很好但现在我想添加已在下面的代码中注释掉的值

foreach($jsonObj->d->results as $value)
    {   $i = 0;
        $bingArray[str_replace ($find, '', ($value->{'Url'}))] = array(         
        //'title'=> $value->{'Title'},
        //'snippet' => $value->{'Description'},
        'score' => $score--
     );

我确信改变第一个foreach循环很简单但是我不确定如何,请帮助

1 个答案:

答案 0 :(得分:0)

答案是将每个数组元素定义为包含score,title和snippet元素的关联数组。

$combined = array(); 

foreach($bingArray as $key=>$value){ // for each bing item
if(isset($combined[$key]))
    $combined[$key]["score"] += $value['score']; // add the score if already exists in $combined
else
    $combined[$key] = array("score"=>$value['score'],"title"=>$value["title"], "snippet"=>$value["snippet"]); // set initial score if new
}

要访问分数,您只需

echo $combined[$key]["score"];