【问题标题】:Count how often a particular value appears in an array计算特定值在数组中出现的频率
【发布时间】:2010-03-13 00:08:10
【问题描述】:

我知道php的函数count(), 但是计算一个值在数组中出现的频率的函数是什么?

例子:

$array = array(
  [0] => 'Test',
  [1] => 'Tutorial',
  [2] => 'Video',
  [3] => 'Test',
  [4] => 'Test'
);

现在我想计算“测试”出现的频率。

【问题讨论】:

    标签: php arrays count


    【解决方案1】:

    PHP 有一个名为 array_count_values 的函数。

    例子:

    <?php
    $array = array(1, "hello", 1, "world", "hello");
    print_r(array_count_values($array));
    ?>
    

    输出:

    Array
    (
        [1] => 2
        [hello] => 2
        [world] => 1
    )
    

    【讨论】:

      【解决方案2】:

      尝试函数array_count_values,您可以在此处的文档中找到有关该函数的更多信息:http://www.php.net/manual/en/function.array-count-values.php

      来自该页面的示例:

      <?php
      $array = array(1, "hello", 1, "world", "hello");
      print_r(array_count_values($array));
      ?>
      

      将产生:

      Array
      (
          [1] => 2
          [hello] => 2
          [world] => 1
      )
      

      【讨论】:

      • 我需要类似的东西,但我使用的是 Laravel,到目前为止:{{ $comment-&gt;count(['comment']) }} 只返回 comments 列中的所有值。我想计算每个帖子的 cmets 数量。在commentable_id 列中存储了来自帖子的 id。可以想象,随着帖子获得更多 cmets,id 会重复。
      猜你喜欢
      • 2022-11-28
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      • 2018-04-29
      • 2023-02-22
      • 2023-01-20
      • 2019-07-08
      相关资源
      最近更新 更多