6

I would like to sort below array based on amount but I don't know how. Anyone help me

Array(
    [0] => Array
     (
          [id] => 1
          [amount] => 20
     )
     [1] => Array
     (
          [id] => 2
          [amount] => 30
     )
     [2] => Array
     (
          [id] => 3
          [amount] => 10
     )
)
ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
Sridhar G
  • 93
  • 1
  • 1
  • 11

4 Answers4

9

Something like

PHP7+

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

What is <=> (the 'Spaceship' Operator) in PHP 7?

< PHP 7

 usort($array, function($a, $b){
     if( $a['amount'] == $b['amount'] )
        return 0;
     else if($a['amount'] > $b['amount'])
        return 1;
     else
        return -1
 });

OR you can just subtract them like everyone else...

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
2

usort [1] will do the job using a custom comparator function which indexes into the amount property and performs a standard integer comparison for less than/greater than. Sort descending with $b["amount"] - $a["amount"] if you wish.

$data = [
  [
    "id" => 1,
    "amount" => 20
  ],
  [
    "id" => 2,
    "amount" => 30,
  ],
  [
    "id" => 3,
    "amount" => 10
  ]
];

usort($data, function ($a, $b) {
    return $a["amount"] - $b["amount"];
});

print_r($data);

Output:

Array
(
    [0] => Array
        (
            [id] => 3
            [amount] => 10
        )

    [1] => Array
        (
            [id] => 1
            [amount] => 20
        )

    [2] => Array
        (
            [id] => 2
            [amount] => 30
        )

)
ggorlen
  • 44,755
  • 7
  • 76
  • 106
1

Use usort.

E.g

function sortByAmount($x, $y) {
    return $x['amount'] - $y['amount'];
}

usort($array, 'sortByAmount');
echo "<pre>"; print_r($array);
Manish Chauhan
  • 595
  • 2
  • 7
  • 14
1

Use usort function like this (know more about usort click here):

  $array = array(array('id'=>1,'amount'=>20),array('id'=>2,'amount'=>30),array('id'=>3,'amount'=>10));

Create custom function like this:

function sortByAmount($x,$y){
  return $x['amount']-$y['amount'];
}

Then use usort function like this:

usort($array,'sortByAmount');
// then print
echo"<pre>"; print_r($array);
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83