Remove unique elements from array

时间:2016-03-04 17:56:10

标签: php arrays

So I've been trying to find a solution to remove unique elements from an object array and keep the duplicates but almost all the questions are on how to remove duplicates.

The array looks like this:

[{"No":"123","Product":"Name X","Color":"blue"},
 {"No":"123","Product":"Name X","Color":"green"},
 {"No":"456","Product":"Name X2","Color":"red"},
 {"No":"456","Product":"Name X2","Color":"blue"},
 {"No":"789","Product":"Name X3","Color":"yellow"}]

I need to check No if it's unique and remove it if it is. The array would look like this afterwards:

[{"No":"123","Product":"Name X","Color":"blue"},
 {"No":"123","Product":"Name X","Color":"green"},
 {"No":"456","Product":"Name X2","Color":"red"},
 {"No":"456","Product":"Name X2","Color":"blue"}]

I tried doing get only the duplicates in the first place (MySQL), but all the solutions involved using GROUP BY and HAVING which did return only the duplicate rows but did also combine them.

2 个答案:

答案 0 :(得分:1)

So you want to remove numbers that only appear once. You can do this in two "passes".

First, build the list of numbers and how often they appear:

$numbers = array_reduce(
    $input,
    function($carry,$value) {
        if( !isset($carry[$value['No']])) $carry[$value['No']] = 0;
        $carry[$value['No']]++;
        return $carry;
    },
    []
);
$uniques = array_filter($numbers,function($n) {return $n == 1;});

Now you have a list of unique numbers. So you can strip out the ones that match those numbers.

$result = array_filter(
    $input,
    function($item) use ($uniques) {
        return !isset($uniques[$item['No']]);
    }
);

Done.

答案 1 :(得分:0)

我会选择这样的事情:

$db_result = array(); // Your array with duplicates

$count_occurrences = array();

foreach($db_result as $k=>&$v)
{
    $count_occurrences[$v['No']] = array(
        'key'=>$k,
        'count'=>(isset($count_occurrences[$v['No']]['count']) ? ($count_occurrences[$v['No']]['count'] + 1) : 1)
    );
}
unset($v);

foreach($count_occurrences as &$v)
{
    if($v['count'] === 1)
    {
        unset($db_result[$v['key']]);
    }
}
unset($v);