计算并显示数组中唯一值的出现次数

发布于 2024-07-29 02:26:36 字数 321 浏览 8 评论 0原文

我正在 PHP 中使用一维数组。 我想检测重复值的存在,然后计算重复值的数量并输出结果。 例如,给定以下数组:

$array = [
    'apple',
    'orange',
    'pear',
    'banana',
    'apple',
    'pear',
    'kiwi',
    'kiwi',
    'kiwi'
];

我想打印:

apple (2)
orange
pear (2)
banana
kiwi (3)

关于如何解决此问题的任何建议?

I am working with a one dimensional array in PHP. I would like to detect the presence of duplicate values, then count the number of duplicate values and output the results. For example, given the following array:

$array = [
    'apple',
    'orange',
    'pear',
    'banana',
    'apple',
    'pear',
    'kiwi',
    'kiwi',
    'kiwi'
];

I would like to print:

apple (2)
orange
pear (2)
banana
kiwi (3)

Any advice on how to approach this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

笑脸一如从前 2024-08-05 02:26:36

您可以使用 array_count_values 函数

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');

print_r(array_count_values($array));

将输出

Array
(
   [apple] => 2
   [orange] => 1
   [pear] => 2
   etc...
)

You can use array_count_values function

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');

print_r(array_count_values($array));

will output

Array
(
   [apple] => 2
   [orange] => 1
   [pear] => 2
   etc...
)
你不是我要的菜∠ 2024-08-05 02:26:36
if(count(array_unique($array))<count($array))
{
    // Array has duplicates
}
else
{
    // Array does not have duplicates
}
if(count(array_unique($array))<count($array))
{
    // Array has duplicates
}
else
{
    // Array does not have duplicates
}
固执像三岁 2024-08-05 02:26:36
function array_not_unique( $a = array() )
{
    return array_diff_key( $a , array_unique( $a ) );
}

结果:(演示

array (
  4 => 'apple',
  5 => 'pear',
  7 => 'kiwi',
  8 => 'kiwi',
)
function array_not_unique( $a = array() )
{
    return array_diff_key( $a , array_unique( $a ) );
}

Result: (Demo)

array (
  4 => 'apple',
  5 => 'pear',
  7 => 'kiwi',
  8 => 'kiwi',
)
溺渁∝ 2024-08-05 02:26:36

您可以尝试将该数组转换为关联数组,其中水果作为键,出现次数作为值。 有点啰嗦,但看起来像:

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
   'pear', 'kiwi', 'kiwi', 'kiwi');
$new_array = array();
foreach ($array as $key => $value) {
    if(isset($new_array[$value]))
        $new_array[$value] += 1;
    else
        $new_array[$value] = 1;
}
foreach ($new_array as $fruit => $n) {
    echo $fruit;
    if($n > 1)
        echo "($n)";
    echo "<br />";
}

You could try turning that array into a associative array with the fruits as keys and the number of occurrences as values. Bit long-winded, but it looks like:

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
   'pear', 'kiwi', 'kiwi', 'kiwi');
$new_array = array();
foreach ($array as $key => $value) {
    if(isset($new_array[$value]))
        $new_array[$value] += 1;
    else
        $new_array[$value] = 1;
}
foreach ($new_array as $fruit => $n) {
    echo $fruit;
    if($n > 1)
        echo "($n)";
    echo "<br />";
}
仙气飘飘 2024-08-05 02:26:36

要摆脱它,请使用array_unique()。 要检测是否有任何使用 count(array_unique()) 并与 count($array) 进行比较。

To get rid use array_unique(). To detect if have any use count(array_unique()) and compare to count($array).

白云悠悠 2024-08-05 02:26:36

也许是这样的(未经测试的代码,但应该给你一个想法)?

$new = array();

foreach ($array as $value)
{
    if (isset($new[$value]))
        $new[$value]++;
    else
        $new[$value] = 1;
}

然后你将得到一个新数组,其中的值作为键,它们的值是它们在原始数组中存在的次数。

Perhaps something like this (untested code but should give you an idea)?

$new = array();

foreach ($array as $value)
{
    if (isset($new[$value]))
        $new[$value]++;
    else
        $new[$value] = 1;
}

Then you'll get a new array with the values as keys and their value is the number of times they existed in the original array.

百思不得你姐 2024-08-05 02:26:36

将它们填充到 map 中(伪代码)

map[string -> int] $m
foreach($word in $array)
{
    if(!$m.contains($word))
        $m[$word] = 0;

    $m[$word] += 1;
}

Stuff them into a map (pseudocode)

map[string -> int] $m
foreach($word in $array)
{
    if(!$m.contains($word))
        $m[$word] = 0;

    $m[$word] += 1;
}
再可℃爱ぅ一点好了 2024-08-05 02:26:36

我没有找到我想要的答案,所以我写了这个函数。 这将生成一个仅包含两个数组之间的重复项的数组,但不会打印元素重复的次数,因此它不能直接回答问题,但我希望它能对我这种情况的人有所帮助。

function findDuplicates($array1,$array2)
{
    $combined = array_merge($array1,$array2);
    $counted = array_count_values($combined);
    $dupes = [];
    $keys = array_keys($counted);
    foreach ($keys as $key)
    {   
        if ($counted[$key] > 1)
        {$dupes[] = $key;}
    }
    sort($dupes);
    return $dupes;
}
$array1 = [1,2,3,4,5];
$array2 = [4,5,6,7,8];
$dupes = findDuplicates($array1,$array2);
print_r($dupes);

输出:

Array
(
    [0] => 4
    [1] => 5
)

I didn't find the answer I was looking for, so I wrote this function. This will make an array that contains only the duplicates between the two arrays, but not print the number of times an element is duplicated, so it's not directly answering the question, but I'm hoping it'll help someone in my situation.

function findDuplicates($array1,$array2)
{
    $combined = array_merge($array1,$array2);
    $counted = array_count_values($combined);
    $dupes = [];
    $keys = array_keys($counted);
    foreach ($keys as $key)
    {   
        if ($counted[$key] > 1)
        {$dupes[] = $key;}
    }
    sort($dupes);
    return $dupes;
}
$array1 = [1,2,3,4,5];
$array2 = [4,5,6,7,8];
$dupes = findDuplicates($array1,$array2);
print_r($dupes);

Outputs:

Array
(
    [0] => 4
    [1] => 5
)
俯瞰星空 2024-08-05 02:26:36
$data = ['outer', 'inner', 'sole', 'sole', 'outer', 'outer'];

$result = max(array_count_values($data));

if($result > 1) {
  echo 'Duplicate items were found!';
}

我认为这种方式更短、更干净。

$data = ['outer', 'inner', 'sole', 'sole', 'outer', 'outer'];

$result = max(array_count_values($data));

if($result > 1) {
  echo 'Duplicate items were found!';
}

I think this way is shorter and cleaner.

未蓝澄海的烟 2024-08-05 02:26:36
function array_not_unique(array $array): array
    {
        $duplicate_array = array_diff_key( $array , array_unique( $array ) );
        $unique_array = [];
        foreach ($array as $key => $value) {
            if ( in_array($value, $duplicate_array)) {
                $duplicate_array[$key] = $value;
            }
            else {
                $unique_array[$key] = $value;
            } 

        }

        return ["unique_array" => $unique_array, "duplicate_array" => $duplicate_array];
    }
function array_not_unique(array $array): array
    {
        $duplicate_array = array_diff_key( $array , array_unique( $array ) );
        $unique_array = [];
        foreach ($array as $key => $value) {
            if ( in_array($value, $duplicate_array)) {
                $duplicate_array[$key] = $value;
            }
            else {
                $unique_array[$key] = $value;
            } 

        }

        return ["unique_array" => $unique_array, "duplicate_array" => $duplicate_array];
    }
楠木可依 2024-08-05 02:26:36

该函数仅提供冗余值

function array_find_redundant($A){
    $U=$N=[];
    foreach($A As $k=>$v){
        if(in_array($v,$U)){$N[$k]=$v;}else{$U[]=$v;}
    }
    return $N;
}

$A = ['A','B','B','C','C','C'];
$B = array_find_redundant($A); // [2=>'B',4=>'C',5=>'C'] 

This function give you the redundant values only

function array_find_redundant($A){
    $U=$N=[];
    foreach($A As $k=>$v){
        if(in_array($v,$U)){$N[$k]=$v;}else{$U[]=$v;}
    }
    return $N;
}

$A = ['A','B','B','C','C','C'];
$B = array_find_redundant($A); // [2=>'B',4=>'C',5=>'C'] 
明媚如初 2024-08-05 02:26:36
$arr = [1,2,2,2,4,5,5,5,8,9,10,2,5,9,10,10];
array_count_values($arr); 
// OUT PUT Array(
//    2 => 4
//    5 => 4
//    9 => 2
//   10 => 3
// )

// If you want unique items
$items = array_keys( array_intersect( array_count_values($arr), [1] ) )

//If you want duplicate items 
$duplicates = array_keys( array_diff( array_count_values($arr), [1] ) )
$arr = [1,2,2,2,4,5,5,5,8,9,10,2,5,9,10,10];
array_count_values($arr); 
// OUT PUT Array(
//    2 => 4
//    5 => 4
//    9 => 2
//   10 => 3
// )

// If you want unique items
$items = array_keys( array_intersect( array_count_values($arr), [1] ) )

//If you want duplicate items 
$duplicates = array_keys( array_diff( array_count_values($arr), [1] ) )
娇柔作态 2024-08-05 02:26:36
$count = 0;
$output ='';
$ischeckedvalueArray = array();
for ($i=0; $i < sizeof($array); $i++) {
    $eachArrayValue = $array[$i];
    if(! in_array($eachArrayValue, $ischeckedvalueArray)) {
        for( $j=$i; $j < sizeof($array); $j++) {
            if ($array[$j] === $eachArrayValue) {
                $count++;
            }
        }
        $ischeckedvalueArray[] = $eachArrayValue;
        $output .= $eachArrayValue. " Repated ". $count."<br/>";
        $count = 0;
    }

}

echo $output;
$count = 0;
$output ='';
$ischeckedvalueArray = array();
for ($i=0; $i < sizeof($array); $i++) {
    $eachArrayValue = $array[$i];
    if(! in_array($eachArrayValue, $ischeckedvalueArray)) {
        for( $j=$i; $j < sizeof($array); $j++) {
            if ($array[$j] === $eachArrayValue) {
                $count++;
            }
        }
        $ischeckedvalueArray[] = $eachArrayValue;
        $output .= $eachArrayValue. " Repated ". $count."<br/>";
        $count = 0;
    }

}

echo $output;
扭转时空 2024-08-05 02:26:36

循环遍历 array_count_values() 返回的键和值,并有条件地打印出现次数(如果大于 1)。

代码:(演示)

foreach (array_count_values($array) as $value => $count) {
    printf("%s%s\n", $value, $count > 1 ? " ($count)" :'');
}

Loop over the keys and values returned by array_count_values() and conditionally print the number of occurrences if greater than one.

Code: (Demo)

foreach (array_count_values($array) as $value => $count) {
    printf("%s%s\n", $value, $count > 1 ? " ($count)" :'');
}
云雾 2024-08-05 02:26:36

一个简单的方法:

$array = array_values(array_unique($array, SORT_REGULAR));

A simple method:

$array = array_values(array_unique($array, SORT_REGULAR));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文