PHP - count frequency of array values

2019-01-20 16:56发布

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条回答
一夜七次
2楼-- · 2019-01-20 17:25

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
)
查看更多
登录 后发表回答