如何计算数组中重复项的出现次数

时间:2012-11-29 20:15:27

标签: php arrays count

我想计算数组中每个重复项的出现次数,最后得到一个只有唯一/不重复项的数组及其各自的出现次数。

这是我的代码;但我不会在哪里出错!

<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);

//$previous[value][Occurrence]

for($arr = 0; $arr < count($array); $arr++){

    $current = $array[$arr];
    for($n = 0; $n < count($previous); $n++){
        if($current != $previous[$n][0]){// 12 is not 43 -----> TRUE
            if($current != $previous[count($previous)][0]){
                $previous[$n++][0] = $current;
                $previous[$n++][1] = $counter++;
            }
        }else{  
            $previous[$n][1] = $counter++;
            unset($previous[count($previous)-1][0]);
            unset($previous[count($previous)-1][1]);
        }   
    }
}
//EXPECTED VALUES
echo 'No. of NON Duplicate Items: '.count($previous).'<br><br>';// 7
print_r($previous);// array( {12,1} , {21,2} , {43,6} , {66,1} , {56,1} , {78,2} , {100,1})
?>    

12 个答案:

答案 0 :(得分:119)

array_count_values,享受: - )

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$vals = array_count_values($array);
echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
print_r($vals);

结果:

No. of NON Duplicate Items: 7
Array
(
    [12] => 1
    [43] => 6
    [66] => 1
    [21] => 2
    [56] => 1
    [78] => 2
    [100] => 1
)

答案 1 :(得分:6)

如果您想在没有'array_count_values'的情况下尝试 你可以在这里做一个聪明的方法

<?php
$input= array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);

$count_values = array();
foreach ($input as $a) {

     @$count_values[$a]++;

}
echo 'Duplicates count: '.count($count_values);
print_r($count_values);
?>

答案 2 :(得分:3)

我实际上最近编写了一个函数来检查数组中的子字符串,在这种情况下会派上用场。

function strInArray($haystack, $needle) {
    $i = 0;
    foreach ($haystack as $value) {
        $result = stripos($value,$needle);
        if ($result !== FALSE) return TRUE;
        $i++;
    }
    return FALSE;
}

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);

for ($i = 0; $i < count($array); $i++) {
    if (strInArray($array,$array[$i])) {
        unset($array[$i]);
    }
}
var_dump($array);

答案 3 :(得分:3)

如果你有一个多维数组,你可以使用PHP 5.5+:

$ pytest /tmp/instance_vectorize.py
======================= test session starts ========================
platform linux -- Python 3.6.5, pytest-3.5.1, py-1.5.3, pluggy-0.6.0
rootdir: /tmp, inifile:
collected 1 item

../../tmp/instance_vectorize.py .                                                                                                                                                     [100%]

==================== 1 passed in 0.08 seconds ======================

返回例如

array_count_values(array_column($array, 'key'))

答案 4 :(得分:2)

PHP为您提供了一个神奇的功能,称为in_array()

使用部分代码,我们将按如下方式修改循环:

<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$arr2 = array();
$counter = 0;
for($arr = 0; $arr < count($array); $arr++){
    if (in_array($array[$arr], $arr2)) {
        ++$counter;
        continue;
    }
    else{
        $arr2[] = $array[$arr];
    }
}
echo 'number of duplicates: '.$counter;
print_r($arr2);
?>

答案 5 :(得分:2)

  
    

在PHP中计算数组的重复元素,而不使用内置函数     功能

  
$arraychars=array("or","red","yellow","green","red","yellow","yellow");
$arrCount=array();
        for($i=0;$i<$arrlength-1;$i++)
        {
          $key=$arraychars[$i];
          if($arrCount[$key]>=1)
            {
              $arrCount[$key]++;
            } else{
              $arrCount[$key]=1;
        }
        echo $arraychars[$i]."<br>";
     }
        echo "<pre>";
        print_r($arrCount);

答案 6 :(得分:1)

您也可以将它与文本项数组一起使用,您将正确获得重复数,但PHP显示

  

警告:array_count_values():只能计算STRING和INTEGER   值!

$domains = 
array (
  0 => 'i1.wp.com',
  1 => 'i1.wp.com',
  2 => 'i2.wp.com',
  3 => 'i0.wp.com',
  4 => 'i2.wp.com',
  5 => 'i2.wp.com',
  6 => 'i0.wp.com',
  7 => 'i2.wp.com',
  8 => 'i0.wp.com',
  9 => 'i0.wp.com' );

$tmp = array_count_values($domains);
print_r ($tmp);

    array (
      'i1.wp.com' => 2730,
      'i2.wp.com' => 2861,
      'i0.wp.com' => 2807
    )

答案 7 :(得分:1)

您可以使用foreach循环来实现。

          $arrayVal = array(1,2,3,1,2,3,1,2,3,4,4,5,6,4,5,6,88);
          $set_array = array();
          foreach ($array as $value) {
            $set_array[$value]++;
          }
           print_r($set_array);

输出:-

  Array( [1] => 3
             [2] => 3
             [3] => 3
             [4] => 3
             [5] => 2
             [6] => 2
             [88] => 1
            )

答案 8 :(得分:0)

我是从谷歌来到这里寻找一种方法来计算数组中重复项目的出现次数。这是简单的方法:

$colors = array("red", "green", "blue", "red", "yellow", "blue");
$unique_colors = array_unique($colors);
// $unique colors : array("red", "green", "blue", "yellow")
$duplicates = count($colors) - count($unique_colors);
// $duplicates = 6 - 4 = 2
if( $duplicates == 0 ){
 echo "There are no duplicates";
}
echo "No. of Duplicates are :" . $duplicates;

// Output: No. of Duplicates are: 2

array_unique()的工作原理是什么?

它构成了所有重复的元素。 的例如: 让我们说我们有一个数组如下 -

$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [3]=>"ferrari", [4]=>"Bugatti");

执行$cars = array_unique($cars);时 汽车将只有以下元素。 $cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [4]=>"Bugatti");

阅读更多内容:https://www.w3schools.com/php/func_array_unique.asp

希望对于那些从谷歌来这里寻找计算数组中重复值的方法的人有所帮助。

答案 9 :(得分:0)

此代码将在同一数组中返回重复值

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
  if(array_count_values($arr)[$item] > 1){
     echo "Found Matched value : ".$item." <br />";
  }
}

答案 10 :(得分:0)

$search_string = 4;
$original_array = [1,2,1,3,2,4,4,4,4,4,10];
$step1 = implode(",", $original_array); // convert original_array to string
$step2 = explode($search_string, $step1); // break step1 string into a new array using the search string as delimiter
$result = count($step2)-1; // count the number of elements in the resulting array, minus the first empty element
print_r($result); // result is 5

答案 11 :(得分:-1)

    $input = [1,2,1,3,2,4,10];
    //if give string
    //$input = "hello hello how are you how hello";
    //$array = explode(' ',$input);
    $count_val = [];
    foreach($array as $val){
      $count_val[$val]++;
    }
    print_r($count_val);
//output ( [1] => 2 [2] => 2 [3] => 1 [4] => 1 [10] => 1 )