doulin1867 2016-01-14 07:45
浏览 76
已采纳

php如何按频率顺序对多个数组中的值进行排序

I have an array containing multiple arrays like

$A = array();
$A[0] = array("1","2","3","4","5");
$A[1] = array("1","6","7","8");
$A[2] = array("0","1","3");

I want to sort the values in multiple arrays in the order of frequency and put them into another array let's say $B.

The values in $B is "1","1","1","3","3","0","2","4","5","6","7","8".

  • 写回答

5条回答 默认 最新

  • dongqiyou0303 2016-01-14 08:21
    关注

    $A = array();
    $A[0] = array("1","2","3","4","5");
    $A[1] = array("1","6","7","8");
    $A[2] = array("0","1","3");
    
    //Merging above array in to one array
    $merged = array_values(call_user_func_array('array_merge', $A));
    //Getting occurrence count
    $counts = array_count_values($merged);
    //Sort by count
    arsort($counts);
    
    //Adding to required array
    $B = array();
    foreach ($counts as $k => $v)
        for($i=1;$i<=$v;$i++)
            $B[] = $k;
    
    echo "<pre>";
    print_r($B);
    echo "</pre>";

    Result

    Array
    (
        [0] => 1
        [1] => 1
        [2] => 1
        [3] => 3
        [4] => 3
        [5] => 0
        [6] => 8
        [7] => 7
        [8] => 5
        [9] => 2
        [10] => 4
        [11] => 6
    )
    
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?