1

I have an array as following and I want to order that array ascending and descending by the value of the key "min_price". I tried and I followed this link still not working properly. Any help would be greatly appreciated.

This is the array:

    Array
    (
        [0] => Array
            (
                [property_id] => 116 
                [min_price] => 3487
            )

        [1] => Array
            (
                [property_id] => 131
                [min_price] => 3035
            )

        [2] => Array
            (
                [property_id] => 171
                [min_price] => 7999
            )
    )

      function cmp($a, $b) {
    if ($a['min_price'] == $b['min_price']) {
        return 0;
    }
    return ($a['min_price'] < $b['min_price']) ? -1 : 1;
} 
uasort($data, 'cmp');

I want to use this array ascending and descending order.

Community
  • 1
  • 1
sandip kakade
  • 1,346
  • 5
  • 23
  • 49

2 Answers2

0

You could use the new Combined Comparison Operator(AKA Spaceship) (Since php-7):

// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

More info in the announcement.

So you could write:

usort($Array, function($a, $b) {
                                 return $a['min_price'] <=> $b['min_price']; 
                               });

Hope this help

Matteo
  • 37,680
  • 11
  • 100
  • 115
0

here is an example of sorting

<?php
  $array = array(
  0 =>array(
      'name' => 'Rnukir',
      'total' => '1'),
  1 => array(
      'name' => 'Arnesista',
      'total' => '2'),
  2 => array(
      'name' => 'Omas',
      'total' => '3'),
  3 => array(
      'name' => 'John',
      'total' => '4')
);
foreach ($array as $key => $row) {
    $name[$key]  = $row['name'];
    $total[$key] = $row['total'];
}
 print_r($total);

 array_multisort($total, SORT_DESC, $array);
//  array_multisort($total, SORT_DESC, $name, SORT_ASC $array);
echo "<pre>";
  print_r($array);
echo "</pre>";
?> 
Piyush
  • 74
  • 6