计算并显示数组中唯一值的出现次数
我正在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
您可以使用 array_count_values 函数
将输出
You can use array_count_values function
will output
结果:(演示)
Result: (Demo)
您可以尝试将该数组转换为关联数组,其中水果作为键,出现次数作为值。 有点啰嗦,但看起来像:
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_unique()
。 要检测是否有任何使用count(array_unique())
并与count($array)
进行比较。To get rid use
array_unique()
. To detect if have any usecount(array_unique())
and compare tocount($array)
.也许是这样的(未经测试的代码,但应该给你一个想法)?
然后你将得到一个新数组,其中的值作为键,它们的值是它们在原始数组中存在的次数。
Perhaps something like this (untested code but should give you an idea)?
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.
将它们填充到
map
中(伪代码)Stuff them into a
map
(pseudocode)我没有找到我想要的答案,所以我写了这个函数。 这将生成一个仅包含两个数组之间的重复项的数组,但不会打印元素重复的次数,因此它不能直接回答问题,但我希望它能对我这种情况的人有所帮助。
输出:
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.
Outputs:
我认为这种方式更短、更干净。
I think this way is shorter and cleaner.
该函数仅提供冗余值
This function give you the redundant values only
循环遍历
array_count_values()
返回的键和值,并有条件地打印出现次数(如果大于 1)。代码:(演示)
Loop over the keys and values returned by
array_count_values()
and conditionally print the number of occurrences if greater than one.Code: (Demo)
一个简单的方法:
A simple method: