Sorting 2-dimensional arrays in PHP (multi-dimensional array)
There have been numerous occasions where we have retrieved the result of an array and yet still needed to do some kind of sorting. Up until now it seemed like there was no answer. The answer was found with the function array_multisort. The names of some PHP functions can be quite misleading but this one does what it says.
The trick to using this function is that it sorts based on columns. The normal layout of a database table returned into an array is with each row of the table is a seperate element of an array. The 2nd dimension of the array has the table row names as the keys with the value attached.

So there is our table represented in an array with each element as a separate row. To sort we need an array for each column, in this case fruit and color. We use the following code to accomplish this.
foreach ($query_result as $key => $row) { $fruit[$key] = $row['fruit']; $color[$key] = $row['color']; }
It seems quite unintuitive but essentially each column is a separate array with the row number being the key. Now we are able to plug this new data into the array_multisort function to sort our existing array (NOTE: the new column based arrays we created are specifically for the purpose of sorting)
array_multisort($color, SORT_DESC, $fruit, SORT_ASC, $query_result);
Basically you list the order of columns you want to search by. In this case we’re sorting by color descending first and then by fruit ascending. The last parameter is the multi-dimensional array that you want to sort.
Seems like a convoluted way of a simple sort. It’s always best to do all sorting and querying in the database but for the few situations that just isn’t possible, we have a solution using array_multisort in PHP.
