简体   繁体   中英

How to sort a array according to 2 value

I have an array that I would like sort according to 2 value. first I want to sort it according to c_gpa value. if c_gpa value is equal with other value in the array then sort t_mark value.

Here is my array

$array = array(
        [0]=>array(
            "roll_number" => 1,
            "c_gpa" => 4.8,
            "t_mark"=>750
        ),
        [1] => array(
            "roll_number" => 2,
            "c_gpa" => 4.12,
            "t_mark"=>530
        ),
        [2] => array(
            "roll_number" => 3,
            "c_gpa" => 4.12,
            "t_mark"=>550
        )

);

I wrote below code for sort c_gpa value but there 2 value is same (4.12) so I want to sort it 't_mark' value these array

usort($array, "all_filter");
    function all_filter($a,$b) {
        return $a['c_gpa'] < $b['c_gpa'];

     }

my expected output is.

$array = array(
        [0]=>array(
            "roll_number" => 1,
            "c_gpa" => 4.8,
            "t_mark"=>750
        ),
        [1] => array(
            "roll_number" => 3,
            "c_gpa" => 4.12,
            "t_mark"=>550
        ),          
        [2] => array(
            "roll_number" => 2,
            "c_gpa" => 4.12,
            "t_mark"=>530
        )

);

Thanks in advance!!!

You can able to do this using array_multisort function.

<?php
// Obtain a list of columns
foreach ($array as $key => $row) {
    $c_gpa[$key]  = $row['c_gpa'];
    $t_mark[$key] = $row['t_mark'];
}

// Sort the data array with $c_gpa ASC, $t_mark ASC
// Add $data as the last parameter, to sort by the common key
array_multisort($c_gpa, SORT_DESC, $t_mark, SORT_ASC, $array);
var_dump($array);
?>

array_multisort documentation

if you want to use usort() , you can use it like this, and the demo

   <?php
    $array = array(
            array(
                "roll_number" => 1,
                "c_gpa" => 4.8,
                "t_mark"=>750
            ),
            array(
                "roll_number" => 2,
                "c_gpa" => 4.12,
                "t_mark"=>530
            ),
            array(
                "roll_number" => 3,
                "c_gpa" => 4.12,
                "t_mark"=>550
            ));
    usort($array, function($a, $b){
      return $a['c_gpa'] > $b['c_gpa'] ? true : $a['c_gpa'] < $b['c_gpa'] ? false : $a['t_mark'] < $b['t_mark'] ? true : false;
    });
    var_dump($array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM