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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13633954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:48:59  来源:igfitidea点击:

How do I count occurrence of duplicate items in array

phparrayscount

提问by mukamaivan

I would like to count the occurrence of each duplicate item in an array and end up with an array of only unique/non duplicate items with their respective occurrences.

我想计算数组中每个重复项的出现次数,并最终得到一个仅包含唯一/非重复项及其各自出现次数的数组。

Here is my code; BUT I don't where am going wrong!

这是我的代码;但我不知道哪里出错了!

<?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})
?>    

回答by Rocket Hazmat

array_count_values, enjoy :-)

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);

Result:

结果:

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

回答by Sam T

if you want to try without 'array_count_values'you can do with a smart way here

如果你想在没有'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);
?>

回答by Jeremy1026

I actually wrote a function recently that would check for a substring within an array that will come in handy in this situation.

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

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);

回答by PHZ.fi-Pharazon

If you have a multi-dimensional array you can use on PHP 5.5+ this:

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

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

which returns e.g.

返回例如

 [
   'keyA' => 4,
   'keyB' => 2,
 ]

回答by user3040433

You can do it using foreach loop.

您可以使用 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);

Output :-

输出 :-

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

回答by Rupesh Wankhede

Count duplicate element of an array in PHP without using in-built function

在不使用内置函数的情况下计算 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);

回答by wtfowned

You can also use it with text items array, u will get number of duplicates properly, but PHP shows

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

Warning: array_count_values(): Can only count STRING and INTEGER values!

警告: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
    )

回答by SaidbakR

There is a magical function PHP is offering to you it called in_array().

PHP 为您提供了一个名为in_array()的神奇函数。

Using parts of your code we will modify the loop as follows:

使用您的部分代码,我们将修改循环如下:

<?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);
?>

The above code snippet will return the number total number of repeated items i.e. form the sample array43 is repeated 5 times, 78 is repeated 1 time and 21 is repeated 1 time, then it returns an array without repeat.

上面的代码片段将返回重复项的总数,即样本数组43 重复 5 次,78 重复 1 次,21 重复 1 次,然后返回一个没有重复的数组。

回答by Sahith Vibudhi

I came here from google looking for a way to count the occurence of duplicate items in an array. Here is the way to do it simply:

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

$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

How array_unique() works?

array_unique() 如何工作?

It elements all the duplicates. ex:Lets say we have an array as follows -

它包含所有重复项。 例如:假设我们有一个数组如下 -

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

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

When you do $cars = array_unique($cars);cars will have only following elements. $cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [4]=>"Bugatti");

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

To read more: https://www.w3schools.com/php/func_array_unique.asp

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

Hope it is helpful to those who are coming here from google looking for a way to count duplicate values in array.

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

回答by Salman Saleem

this code will return duplicate value in same array

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

$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 />";
  }
}