找出有多少重复的数组元素

时间:2015-11-29 09:09:12

标签: php arrays duplicates

这是数组和代码

 $array = array(1, 3, 3, 7, 9, 9, 9, 9, 11, 11, 12, 14); 
 $c = array_count_values($array);
 print_r($c);

我得到的输出如下:

Array
(
    [1] => 1
    [3] => 2
    [7] => 1
    [9] => 4
    [11] => 2
    [12] => 1
    [14] => 1
)

我想获得大于或等于2的值的数量,即([3],[9],[11])

Duplicate groups: 3

3 个答案:

答案 0 :(得分:2)

使用array_filter功能过滤掉重复项:

$array = array(1, 3, 3, 7, 9, 9, 9, 9, 11, 11, 12, 14); 
$c = array_count_values($array);
$c = array_filter($c, function($v){return $v > 1;});
$c = count($c);

echo "Duplicate groups: $c";

答案 1 :(得分:1)

  

我想得到的数值> 2([3],[9],[11]):

你的意思是大于或等于2.在这种情况下,我们会>=

$array = array(1, 3, 3, 7, 9, 9, 9, 9, 11, 11, 12, 14);
$c = array_count_values($array);

$r = array();
foreach($c as $k => $v) {
    if($v >= 2) {
        $r[$k] = $v;
    }
}

print "Duplicate groups: " . count($r);

答案 2 :(得分:1)

改进版本:

$array = array(1, 3, 3, 7, 9, 9, 9, 9, 11, 11, 12, 14); 
$array1 = array_count_values($array);
$array2 = array();
foreach($array1 as $key => $value){
  if($value > 1){
    $array2[$key] = $value;
  }
}
print "Duplicate groups: ".count($array2);