2

I have an array(below). I want to sort it by 2 different values, first by the value in "override" which will be an integer 1-9. Then if 0 or null, I want the array to sort by "total_rank". So if override has 3 different values 213, and then total rank being 1.4, 1.6, 1.2, The array would be re-organized to first the row with override - 1, 2, 3. The next row would be the row with total_rank being 1.2, then 1.4, 1.6.

Sorry if I'm not explaining this as clear as I would like to. I tried using arsort(), but couldnt get it to do what I want (I'm new to PHP).

Any help would be appreciated, A sample of a row of the multidimensional array is below:

 array(16) {
  ["id"]=>
  string(1) "3"
 ["title"]=>
  string(5) "test2"
  ["description"]=>
  string(5) "test2"
  ["requester"]=>
  string(1) "1"
  ["project_id"]=>
  string(1) "2"
  ["client_ranking"]=>
  string(1) "5"
  ["tech_ranking"]=>
  string(1) "5"
  ["time_ranking"]=>
  string(1) "5"
  ["pm_ranking"]=>
  string(1) "5"
  ["total_rank"]=>
  string(3) "1.8"
  ["datecreated"]=>
  string(19) "2012-01-05 11:58:13"
  ["dateclosed"]=>
  string(19) "2012-01-05 11:58:13"
  ["ispending"]=>
  string(1) "1"
  ["isclosed"]=>
  string(1) "0"
  ["override"]=>
  string(1) "5"
  ["developer"]=>
  string(1) "1"
Josh
  • 8,082
  • 5
  • 43
  • 41
  • have you looked at `array_multisort`? – topherg Jan 07 '12 at 01:09
  • Dup of [Sorting multi-dimentional array by more than one field](http://stackoverflow.com/questions/2155117/), [Sorting multidimensional array in PHP](http://stackoverflow.com/questions/2059255/), [Sorting PHP array using subkey-values](http://stackoverflow.com/questions/6570146/) – outis Jan 07 '12 at 01:09
  • Can you clarify what you want to sort here? What would you expect the final result to be? Do you have *many* of these arrays which you want to sort? – deceze Jan 07 '12 at 01:11
  • 2
    [`var_export`](http://sscce.org/) produces valid PHP, which is more useful than a dump when the array is to be used in code. – outis Jan 07 '12 at 01:12

1 Answers1

1

If I understood you correctly, you could try using usort:

function cmp($a, $b)
{
    // if 'override' is same we compare 'total_rank'
    if ($a['override'] == $b['override']) {
        if ($a['total_rank'] == $b['total_rank'])
            return 0;
        return ($a['total_rank'] < $b['total_rank']) ? -1 : 1;
    }
    // else compare 'override'
    return ($a['override'] < $b['override']) ? -1 : 1;
}
usort($array, "cmp");
Ranty
  • 3,333
  • 3
  • 22
  • 24