首先对出现次数最多的值进行排序
假设我有一个像这样的数组:
$array = array('a', 'b', 'c', 'c', 'c', 'd', 'a', 'b', 'b', 'b', 'b');
我想要做的是返回一个按包含术语的频率重新排序的数组。所以,像这样:
['b', 'c', 'a', 'd']
因为b
出现了5次,c
出现了三次,a
出现了两次,d
出现了只有一次。这将如何完成?
期望的结果:
array (
0 => 'b',
1 => 'b',
2 => 'b',
3 => 'b',
4 => 'b',
5 => 'c',
6 => 'c',
7 => 'c',
8 => 'a',
9 => 'a',
10 => 'd',
)
Let's say I have an array like this:
$array = array('a', 'b', 'c', 'c', 'c', 'd', 'a', 'b', 'b', 'b', 'b');
What I want to do is return an array reordered by the frequency of included terms. So, like this:
['b', 'c', 'a', 'd']
Because b
appeared 5 times, c
appeared thrice, a
appeared twice, and d
appeared only once. How would this be done?
Desired result:
array (
0 => 'b',
1 => 'b',
2 => 'b',
3 => 'b',
4 => 'b',
5 => 'c',
6 => 'c',
7 => 'c',
8 => 'a',
9 => 'a',
10 => 'd',
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该有帮助
http://www.php.net/manual/ en/function.array-count-values.php
直接来自手册页
然后根据值重新排序
This should help
http://www.php.net/manual/en/function.array-count-values.php
Straight from the man page
Then just reorder based on the values
前面的两个答案都没有对输入数组实现任何类型的排序。
代码:(演示)
请记住,如果您有两个具有相同出现频率的不同值,那么您可能会看到结果中混合了这些值。为了确保相似值分组在一起,请使用辅助排序规则。 (演示)
第二个代码段将按计数降序排序,然后按值升序排序。
Neither of the earlier answers are implementing any kind of sort upon the input array.
Code: (Demo)
Bear in mind that if you have two different values that have the same frequency of occurrence, then you might see the values mixed in the result. To ensure that like-values are grouped together, use a secondary sorting rule. (Demo)
This second snippet will sort by counts descending, then by value ascending.