Link to home
Create AccountLog in
Avatar of yoshcomputers
yoshcomputers

asked on

subsort multidimensional array

I have a multidimensional array that I want to sort by one field then by a second field but retain all the indexes and other fields

Here is the example:
$thisArray[0]["Score"] = 10
$thisArray[0]["SecondScore"] = 15
$thisArray[1]["Score"] = 10
$thisArray[1]["SecondScore"] = 16
$thisArray[2]["Score"] = 10
$thisArray[2]["SecondScore"] = 13
$thisArray[3]["Score"] = 12
$thisArray[3]["SecondScore"] = 12
$thisArray[4]["Score"] = 12
$thisArray[4]["SecondScore"] = 11
$thisArray[5]["Score"] = 12
$thisArray[5]["SecondScore"] = 12

I want to be able Sort them First by Score and Then by SecondScore
so that my results will be
$thisArray[3]["Score"] = 12
$thisArray[3]["SecondScore"] = 12
$thisArray[5]["Score"] = 12
$thisArray[5]["SecondScore"] = 12
$thisArray[4]["Score"] = 12
$thisArray[4]["SecondScore"] = 11
$thisArray[1]["Score"] = 10
$thisArray[1]["SecondScore"] = 16
$thisArray[0]["Score"] = 10
$thisArray[0]["SecondScore"] = 15
$thisArray[2]["Score"] = 10
$thisArray[2]["SecondScore"] = 13
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

I doubt if you can do that, if you insist on preserving numeric keys.  I think you might need to create non-numeric keys, perhaps by prepending a letter to the numbers.  You might also think about using an array of objects instead of an array of arrays.

You might be able to use usort() to handle the sorting.
http://php.net/manual/en/function.usort.php
ASKER CERTIFIED SOLUTION
Avatar of yoshcomputers
yoshcomputers

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of Julian Hansen
If you need to preserve the original key values, why not put the key you are trying to preserve into the sub-array - then the keys of the parent array don't matter?
$thisArray[] = array('key' => 1, 'Score' => 10,  'SecondScore' => 15);
$thisArray[] = array('key' => 2, 'Score' => 10, 'SecondScore' = 16);
...
Then usort and don't worry about the final array keys
Avatar of yoshcomputers
yoshcomputers

ASKER

It is working from my limited testing with two columns to sort on, but has not been performance tested nor tested beyond two column sort