PHP:数组中最常见的值 [英] PHP: Most frequent value in array
本文介绍了PHP:数组中最常见的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有这个 JSON 数组:
So I have this JSON Array:
[0] => 238
[1] => 7
[2] => 86
[3] => 79
[4] => 55
[5] => 92
[6] => 55
[7] => 7
[8] => 254
[9] => 9
[10] => 75
[11] => 238
[12] => 89
[13] => 238
我将在实际的 JSON 文件中有更多的值.但是通过查看这个,我可以看到 238 和 55 的重复次数比任何其他数字都要多.我想要做的是获取数组中重复次数最多的前 5 个值并将它们存储在一个新的 PHP 数组中.
I will be having more values in the actual JSON file. But by looking at this I can see that 238 and 55 is being repeated more than any other number. What I want to do is get the top 5 most repeated values in the array and store them in a new PHP array.
推荐答案
$values = array_count_values($array);
arsort($values);
$popular = array_slice(array_keys($values), 0, 5, true);
array_count_values()
获取数组中每一项出现的次数arsort()
对数组进行排序反序出现的次数array_keys()
得到实际值是array_count_values()
结果中的数组键array_slice()
给了我们结果的前五个元素
$array = [1,2,3,4,238, 7, 86, 79, 55, 92, 55, 7, 254, 9, 75, 238, 89, 238];
$values = array_count_values($array);
arsort($values);
$popular = array_slice(array_keys($values), 0, 5, true);
array (
0 => 238,
1 => 55,
2 => 7,
3 => 4,
4 => 3,
)
这篇关于PHP:数组中最常见的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文