PHP - 数组值的计数频率 [英] PHP - count frequency of array values

查看:121
本文介绍了PHP - 数组值的计数频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在PHP的方式来计算价值在一个大阵多久存在?

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...
    )

我见过的PHP array_count_values​​,但这个被大多数排序 - >最少?还是有更简单的方法?

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

谢谢大家!

推荐答案

进行排序它们与 计数后arsort()

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
)

这篇关于PHP - 数组值的计数频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆