phpsortingksort

Sort array with numbers descending


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) {
                }

Solution

  • Use usort:

    usort($yourArray, function($a, $b) {
        if ($a['value'] == $b['value']) {
            return 0;
        }
        return ($a['value'] < $b['value']) ? -1 : 1;
    });