I am looking to be able to sort an array of multidimensional arrays on multiple columns. To complicate this even further, I would like to be able to set certain sorting options for each key / column. I have something that looks like the result of a database query, but it doesn't really come from one, so you need to sort it in PHP, not SQL.
Array ( [0] => Array ( [first_name] => Homer [last_name] => Simpson [city] => Springfield [state] => Unknown [zip] => 66735 ) [1] => Array ( [first_name] => Patty [last_name] => Bouvier [city] => Scottsdale [state] => Arizona [zip] => 85250 ) [2] => Array ( [first_name] => Moe [last_name] => Szyslak [city] => Scottsdale [state] => Arizona [zip] => 85255 ) [3] => Array ( [first_name] => Nick [last_name] => Riviera [city] => Scottsdale [state] => Arizona [zip] => 85255 ) )
I would like to be able to sort it in the same way that can be done with a DB query. Oh, and sometimes the column / key needs to be indicated by number.
What I had in mind was like this:
$sortOptions = array( array( 'city', SORT_ASC, SORT_STRING ), array( 'zip', SORT_DESC, SORT_NUMERIC), array( 2, SORT_ASC, SORT_STRING) // 2='last_name' ); $sorter = new MultiSort($data, $sortOptions ); $sortedData = $sorter->getSortedArray() ; print_r( $jmsSorted);
What I would like to end up with:
Array ( [0] => Array ( [first_name] => Nick [last_name] => Riviera [city] => Scottsdale [state] => Arizona [zip] => 85255 ) [1] => Array ( [first_name] => Moe [last_name] => Szyslak [city] => Scottsdale [state] => Arizona [zip] => 85255 ) [2] => Array ( [first_name] => Patty [last_name] => Bouvier [city] => Scottsdale [state] => Arizona [zip] => 85250 ) [3] => Array ( [first_name] => Homer [last_name] => Simpson [city] => Springfield [state] => Unknown [zip] => 66735 ) )
UPDATE: I think that ideally a solution would lead to a dynamic creation
array_multisort( $city, SORT_ASC, SORT_STRING, $zip, SORT_DESC, SORT_NUMERIC, $last_name, SORT_ASC, SORT_STRING, $inputArray);
The problem is that I do not want to "hard code" these key names there. I tried to create a solution based on Example # 3 Sorting database results from array_multisort() documentation, which ended up using array_multisort() but I cannot find a way to use my dynamically constructed argument list for array_multisort() .
My attempt was to "combine" these arguments together into an array, and then
call_user_func_array( 'array_multisort', $functionArgs);
This leads to
Warning: Parameter 2 to array_multisort() expected to be a reference, value given in...