dtsps2098 2016-04-20 09:10
浏览 59
已采纳

按数字降序排序数组

I've got results from a Quiz I made and the results are in number (total: 44/33/22/11 where A = 11, B = 44 , C = 33, D = 22 for example) I want the results printed on the screen descending so first the highest (44) and then the second, third and then the lowest (11). Got it working (posted another post a hour ago and someone helped me out ) Proble mis I've got 2 more parameters.

for example:

A - 40 - 90 B - 29 - 91 C - 55 - 92 D - 90 - 93

Now I want it to be showed on the screen as D/C/A/B descending by the second parameter ($percent(90/55/29/40)

Code:

               $percentA = $totalA * 4;
                 $percentB = $totalB * 4;
                 $percentC = $totalC * 4;
                 $percentD = $totalD * 4;

                 $letters    = ['A', 'B', 'C', 'D'];
                 $temp_array = [];

                $results = array(
                    'A' => ['percent' => $percentA, 'value'=>'90'],
                    'B' => ['percent' => $percentB, 'value'=>'91'],
                    'C' => ['percent' => $percentC, 'value'=>'92'],
                    'D' => ['percent' => $percentD, 'value'=>'93']
                );
                //rsort($results);
                for($i = 0; $i < count($results); $i++) {
                    $name    = $letters[$i];
                    $percent = $results[$letters[$i]]['percent'];
                    $value   = $results[$letters[$i]]['value'];

                    $new_array = ['name' => $name, 'percent' => $percent ,'value'=>$value];

                    array_push($temp_array, $new_array);
                }

It sorts but it sorts on the key of the array (3/2/1/0) I want to to sort on percent (10/20/30/40 for example)

                krsort($temp_array);


                foreach ($temp_array as $key => $val) {
                }
  • 写回答

1条回答 默认 最新

  • duanqinbi9029 2016-04-20 09:25
    关注

    Use usort:

    usort($yourArray, function($a, $b) {
        if ($a['value'] == $b['value']) {
            return 0;
        }
        return ($a['value'] < $b['value']) ? -1 : 1;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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