Get your sort on! array_multisort()
Posted in Programming on July 15th, 2008 by Jason – Be the first to commentRecently I was working on a project that does a lot of calculations on information stored in a database. My results were stored in an array, and the user info in another. I then had to sort one array, while at the same time maintain a relationship with the other. Well as my head began to steam looking for a solution to something fairly simple I came across array_multisort() and it did the trick!
Let me try to explain the problem and hopefully it will help to understand how to use this function
// I have my first array
$arr1 = array(0=>"f", 1=>"a", 2=>"c", 3=>"d");
// In other words $arr1 holds the values f,a,c and d
// Now for the second array
$arr2 = array(0=>"Bob, 1=>"Sally", 2=>"Fred", 3=>"Jason");
So we have the basic elements set up. Now my program requires to list the information in arr1 in order of grades, a-f with the highest grade listed first. PHP provides us with the sort() function.
// example of php sort() function
sort($arr1);
// our array now has the values a,c,d and f in order
Do you see the problem? Jason (Me) would now be associated with an F and not the D that he deserves. And I worked so hard for that D! So the problem is that you now have to sort the second array in the exact same way as the first array, so that the index of arr1 and arr2 still correlate. Enter the array_multisort(), its times like this you love PHP and how easy it can make life.
// We use the same array... ignoring our previous sort command
array_multisort($arr1, $arr2);
// Now our array contains the following information
// a,c,d and f
// Sally, Fred, Jason, Bob
// Sally => A, Fred => C, Jason => D, Bob => F
Yeah, I got a D! With the array_multisort you can do exactly what it says, sort multiple array while maintaining a link, or way to keep the data together in the arrays.
Although it is much easier to keep all your data inside a database and then have it sort when you retrieve it, sometimes you have to do the sorting outside of the database. This example my not have been the greatest, but it is used just to show how to use it.
One last thing, say the multi sort does not sort it how you want it, well you can change the sort order as well.
// Changing the sort order
array_multisort($arr1, SORT_ASC, $arr2);
// Note that SORT_ASC and SORT_DESC can be interchanged
// depending on what your needs are.
// You can also add multiple sorts
array_multisort($arr1, SORT_ASC, $arr2, SORT_DESC);
This last sort is the same as saying, sort arr1 ascending and then sort arr2 descending. It works very similar to sorting in a spreadsheet.