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;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算