查找数组重复,添加到原始然后删除

时间:2012-07-16 17:26:42

标签: php arrays function

如果在网址中找到重复项,我想:

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

1 个答案:

答案 0 :(得分:0)

我相信这符合您的要求。

根据您提供的所需输出,您似乎希望保留每个条目的数字索引。如果您实际上不需要保留这些数字,则可以删除第二个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;
}

(这是键盘上的a working example。)