-1

I have an array that looks like this :

[0] => Array
(
    [ID] => 1
    [total_1] => 200
    [total_2] => 10
    [total_3] => 420
    [name] => testname1
)

[1] => Array
(
    [ID] => 2
    [total_1] => 900
    [total_2] => 30
    [total_3] => 40
    [name] => testname1
)

[2] => Array
(
    [ID] => 3
    [total_1] => 900
    [total_2] => 40
    [total_3] => 90
    [name] => testname1
)

I need to sort it by the sum of total_1, total_2 and total_3. So, in this example, if I were to output just the ID key in the correct descending sort order, it would be :

3, 2, 1

Can anyone please tell me how to do this in PHP ?

Chris Jones
  • 405
  • 1
  • 6
  • 17
  • 1
    I think [usort](http://php.net/manual/en/function.usort.php) is the function you are looking for – EllisTheEllice Nov 13 '15 at 13:55
  • It's not a "give problem" and "get answers" site. Please show us what you have did till now and the difficulty which you are facing. – Utkal Sinha Nov 13 '15 at 14:01
  • I did spot the other post but couldn't get my head round usort, however Pablo's solution below is perfect and I now understand it :) Thanks folks. – Chris Jones Nov 13 '15 at 14:22

1 Answers1

1

You can use usort function and compare the sum of the values:

function cmp($arr1, $arr2){
    $sum1 = $arr1['total_1'] + $arr1['total_2'] + $arr1['total_3']; 
    $sum2 = $arr2['total_1'] + $arr2['total_2'] + $arr2['total_3'];
    if ($sum1 == $sum2) {
       return 0;
    }
    return ($sum1 < $sum2) ? -1 : 1;
}

usort($array, "cmp");
Pablo Digiani
  • 602
  • 5
  • 9