0

当在 URL 中找到重复项时,我想:

  1. 取“分数”并将其添加到原件中
  2. 获取“引擎”字符串并将其附加到原始字符串
  3. 然后删除整个重复条目
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'
4

1 回答 1

0

我相信这符合您的要求。

根据您提供的所需输出,您似乎希望保留每个条目的数字索引。如果您实际上不需要保留这些数字,则可以删除第二个foreach循环和有关$indices变量的行,然后只需 return $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;
}

(这是键盘上的一个工作示例。)

于 2012-07-16T18:30:41.387 回答