cloud cloud - 1 month ago 7
PHP Question

How to filter this array according to value

I would like to filter the array according to (total_mark keys) value.
I mean The array filter max value to minimum value

$array = Array(
[0] => Array
(
"roll_n" => 1,
"total_mark" => 250
)

[1] => Array
(
"roll_n" => 2,
"total_mark" => 388
)

[2] => Array
(
"roll_n" => 3,
"total_mark" => 518
)

)


My expected output :

$array = Array(
[0] =Array
(
"roll_n" => 1,
"total_mark" => 518
)

[1] = Array
(
"roll_n" => 2,
"total_mark" => 388
)

)


Thanks in advance....

Answer

You can just use usort to sort your type of multi dimensional array:

 usort($array, "custom_sort");

 function custom_sort($a,$b) {
      return $a['total_mark']<$b['total_mark'];
 }
    print_r ($array);

See the PHP reference: USORT

Full PHP file:

<?php
 $array = Array(
            Array
            (
                "roll_n" => 1,
                "total_mark" => 250
            ), Array
            (
                "roll_n" => 2,
                "total_mark" => 388
            ),Array
            (
                "roll_n" => 3,
                "total_mark" => 518
            )
    );

    echo '<pre>';
    print_r($array);
    echo '</pre><hr>';

    echo '<pre>';

     usort($array, "custom_sort");

     function custom_sort($a,$b) {
          return $a['total_mark']<$b['total_mark'];
     }

     $i = 0;
     $array2 = array();
     foreach ($array as $arr){
         $arr['roll_n'] = $i;
         $i++;
         $array2[$i] = ['roll_n' => $i, 'total_mark' => $arr['total_mark']]; 
     }
    print_r ($array2); // Final Output

    echo '</pre>';
?>
Comments