0

I'm facing the following dilema having an array like this:

Array ( 
    [10001] => Array ( [wins] => 0 [played] => 1 [coefficient] => 1 ) 
    [10002] => Array ( [wins] => 1 [played] => 1 [coefficient] => 0 ) 
    [10008] => Array ( [wins] => 1 [played] => 1 [coefficient] => 0 ) 
    [10015] => Array ( [wins] => 1 [played] => 1 [coefficient] => 0 ) 
    [10014] => Array ( [wins] => 2 [played] => 2 [coefficient] => 1 ) 
    [10017] => Array ( [wins] => 0 [played] => 2 [coefficient] => 2 )
)

I need to sort it first by 'wins' then by 'coefficient' so I called array_multisort after building column arrays like this:

array_multisort($wins, SORT_DESC, $coeff, SORT_DESC, $standings_data);

Great, it all works, however, the keys in the final array are indexes from 0 to 5... I looked up the PHP documentation and found that:

array_multisort() can be used to sort several arrays at once, or a multi-dimensional
array by one or more dimensions.
Associative (string) keys will be maintained, but numeric keys will be re-indexed.

It turns out that my keys are interpreted as numeric so they get re-indexed. Obviously I don't want this to happen but I can't figure out a way to change them to strings without actually changing their values which I cannot do.

So boiling down to the question: is there a way to multisort an associative array maintaining its numeric keys?

mmvsbg
  • 3,362
  • 17
  • 46
  • 67
  • You will need to change the keys to strings - even if that means creating a new array. Even if you make the keys strings with values like '10001', they will be cast to integers. You can add a zero to stop this. The string '010001' will not be cast to an integer. – kainaw Sep 16 '14 at 18:24
  • I have no problem creating a new array but adding a leading zero actually changes the value of '10001' to '010001' and I cannot do that since those correspond to ids in a database. And you are correct that casting '10001' to string won't help as it automatically gets casted back to integer... – mmvsbg Sep 16 '14 at 18:43
  • Use `uasort` with an appropriate comparison function that sorts by two criteria, as shown in [the duplicate](http://stackoverflow.com/a/17364128/476). – deceze Sep 16 '14 at 19:03
  • Thank you! I had a problem with usort not maintaining indexes as well but uasort does the trick. – mmvsbg Sep 16 '14 at 20:53

0 Answers0