【问题标题】:PHP order element in an array by their frequency [duplicate]PHP按频率排列数组中的元素[重复]
【发布时间】:2018-03-16 07:56:25
【问题描述】:

我有一个如下所示的数组:

$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);

我想获取最频繁的项目,然后是下一个最频繁的项目,直到我得到最不频繁的项目,然后使用此信息创建另一个数组,如下所示:

$frequencies=array("1"=>4,"4"=>3,"5"=>2,"6"=>1,"7"=>1)

我怎样才能做到这一点,请帮忙。

【问题讨论】:

    标签: php arrays sorting


    【解决方案1】:

    你必须使用array_count_values()

    <?php
    
    $recs = array(1,4,7,1,5,4,1,12,1,4,6,5);
    
    $recs1 = array_count_values($recs);
    
    print_r($recs1);
    

    https://eval.in/973006

    或者,如果您希望数字需要升序(它们是最终数组中的键),请使用 ksort()

    <?php
    
    $recs = array(1,4,7,1,5,4,1,12,1,4,6,5);
    
    $recs1 = array_count_values($recs);
    ksort($recs1);
    print_r($recs1);
    

    https://eval.in/973163

    【讨论】:

      【解决方案2】:
      $recs = array(1,4,7,5,5,4,5,12,1,4,6,5);
      //array_count_values — Counts all the values of an array
      $recs1 = array_count_values($recs);
      //to get the most frequent item followed by the next most 
      //frequent item until I get to the least frequent item 
      //use `arsort` — Sort an array in reverse order and maintain index association
      arsort($recs1);
      print_r($recs1);
      

      Demo

      【讨论】:

      • 像魅力一样工作。谢谢
      猜你喜欢
      • 2015-10-18
      • 1970-01-01
      • 2020-10-19
      • 2021-12-03
      • 1970-01-01
      • 2011-08-24
      • 2018-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多