0

I want to sort an array highest to lowest by the value of amount. My array $res is as follows:

Array
(
    [0] => 1
    [id] => 1
    [1] => Testowy 1
    [user] => Testowy 1
    [2] => 150
    [amount] => 150
    [3] => 1,2,3
    [what] => 1,2,3
    [4] => Polska
    [country] => Polska
    [5] => 1
    [platform] => 1
)
Array
(
    [0] => 2
    [id] => 2
    [1] => Testowy 2
    [user] => Testowy 2
    [2] => 100
    [amount] => 100
    [3] => 1
    [what] => 1
    [4] => United States
    [country] => United States
    [5] => 2
    [platform] => 2
)

I tried using max and arsort, but none of those seem to accept which key they should use for sorting. Any help?

Tomek Buszewski
  • 7,659
  • 14
  • 67
  • 112
  • 3
    [usort](http://php.net/manual/en/function.usort.php)? – brbcoding Aug 14 '13 at 19:23
  • 1
    I'm just guessing here, but if this result is the result of a db query, you could also sort in the query by using e.g. ORDER BY – djheru Aug 14 '13 at 19:26
  • possible duplicate of [Reference: all basic ways to sort arrays and data in PHP](http://stackoverflow.com/questions/17364127/reference-all-basic-ways-to-sort-arrays-and-data-in-php) – deceze Aug 14 '13 at 19:27

3 Answers3

1

Try usort

function cmp($a, $b)
{
    return ($a["amount"]<=$b["amount"])?-1:1;
}

usort($array, "cmp");
Ben Miller
  • 29
  • 7
  • Maybe dont use strcmp, but a simple '>' cause amount is no string at all. Maybe wrong for sorting '1 and 10'. – dognose Aug 14 '13 at 19:38
  • Now you are missing the equal case :) `return ($a["amount"]>=$b["amount"])` (`>=` or `<=` depending on the sorting order) will be enough. – dognose Aug 14 '13 at 19:43
1
usort($res, function ($a, $b){
    return $b['amount'] - $a['amount'];
});
print_r($res);

For versions of PHP < 5.3, use the following:

function cmp($a, $b){
    return $b['amount'] - $a['amount'];
}
usort($res, "cmp");
Expedito
  • 7,771
  • 5
  • 30
  • 43
0

Use sorting functions with user defined comparators, like: usort:

http://php.net/usort

Then your comparator gets two objects and tells (by any logic you want) which one is greater):

function compare($a, $b) {
    $result = -1;
    if( $a["amount"] == $b["amount"]) {
      $result = 0;
    } else {
       if( $a["amount"] > $b["amount"] ) {
          $result = 1;
       }
    }

    return $result;
}

usort($res, "compare");
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141