3

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
  • 20,856
  • 2
  • 21
  • 35
Sridhar G
  • 63
  • 1
  • 10

4 Answers4

4

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
  • 20,856
  • 2
  • 21
  • 35
1

Use usort.

E.g

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

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

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
  • 33,459
  • 6
  • 59
  • 67
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
  • 43,040
  • 110
  • 45
  • 72