【问题标题】:PHP Get element with 5 highest occurrence in an arrayPHP获取数组中出现次数最多的5个元素
【发布时间】:2010-02-01 12:40:01
【问题描述】:

类似的东西:Get the element with the highest occurrence in an array

不同之处在于我需要超过 1 个结果,总共需要 5 个结果。所以(大)数组中出现次数最多的 5 个。

谢谢!

【问题讨论】:

    标签: php sorting arrays


    【解决方案1】:

    PHP 实际上提供了一些方便的array functions 可以用来实现这一点。

    例子:

    <?php
    $arr = array(
        'apple', 'apple', 'apple', 'apple', 'apple', 'apple',
        'orange', 'orange', 'orange',
        'banana', 'banana', 'banana', 'banana', 'banana', 
        'pear', 'pear', 'pear', 'pear', 'pear', 'pear', 'pear', 
        'grape', 'grape', 'grape', 'grape', 
        'melon', 'melon', 
        'etc'
    );
    
    $reduce = array_count_values($arr);
    arsort($reduce);
    var_dump(array_slice($reduce, 0, 5));
    
    // Output:
    array(5) {
        ["pear"]=>      int(7)
        ["apple"]=>     int(6)
        ["banana"]=>    int(5)
        ["grape"]=>     int(4)
        ["orange"]=>    int(3)
    }
    

    编辑:添加了 array_slice,如下面的 Alix 帖子中使用的那样。

    【讨论】:

      【解决方案2】:

      给你:

      $yourArray = array(1, "hello", 1, "world", "hello", "world", "world");
      $count = array_count_values($yourArray);
      
      arsort($count);
      
      $highest5 = array_slice($count, 0, 5);
      
      echo '<pre>';
      print_r($highest5);
      echo '</pre>';
      

      【讨论】:

      • @Matt:谢谢,当我发布我的答案时,我没有意识到您已经在使用 array_count_values() 函数。
      【解决方案3】:

      构建计数数组并将它们倒序排列:

      $mode = array_count_values($input);
      arsort($mode);
      $i = 0;
      foreach ($mode as $k => $v) {
        $i++;
        echo "$i. $k occurred $v times\n";
        if ($i == 5) {
          break;
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2010-11-06
        • 2019-04-29
        • 2012-03-31
        • 1970-01-01
        • 2011-04-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多