doutan4831 2012-04-05 19:35
浏览 20
已采纳

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

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条回答 默认 最新

  • duanchou6534 2012-04-05 19:39
    关注

    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
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊