PHP - count frequency of array values

大憨熊 提交于 2019-12-29 01:51:08

问题


Is there a way in php to count how often a value exists in a large array?

So if I have an array like this:

$array = "1,2,3,4,joe,1,2,3,joe,joe,4,5,1,6,7,8,9,joe";

is there a way to output a new array that tells me (and sorts) which is used most and how many for each?

$result = array(
    [joe] => 4
    [1] => 3
    [2] =>2
    etc...
    )

I've seen the php array_count_values, but can this be sorted by most -> least? or is there an easier way?

Thanks everyone!


回答1:


Sort them after counting them with arsort()

$result = array_count_values(explode(',', $array));
arsort($result);

Array
(
    [joe] => 4
    [1] => 3
    [2] => 2
    [4] => 2
    [3] => 2
    [9] => 1
    [8] => 1
    [5] => 1
    [6] => 1
    [7] => 1
)


来源:https://stackoverflow.com/questions/10034889/php-count-frequency-of-array-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!