当在URL中发现重复时,我想:
- 取"分数"并将其添加到原始分数中
- 获取"engine"字符串并将其附加到原始字符串
- 然后删除整个重复条目
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'
我相信这符合您的要求。
根据您提供的所需输出,您似乎希望保留每个条目的数字索引。如果实际上不需要保留这些数字,可以删除第二个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;
}
(这是代码板上的一个工作示例。)