本文介绍了如何计算数组中重复项的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

array_count_values,享受 :-)

array_count_values, enjoy :-)

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

这篇关于如何计算数组中重复项的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 21:46