I have a multidimensional array that stores people.
Array ( id93294 => (array ( Name => "Tom Anderson", Birthday => "03/17/1975"), id29349 => (array ( Name => "Tom Anderson", Birthday => "03/17/1975") )
Kind of like that except with more info for the people, so I want to first sort by birthdays THEN sort by another attribute (if their hometown matches their current location) but once I do the second sort on the array it loses the first sort I did using the birthdays...
How do I sort multiple times without it messing up my previous sorts.
P.S. I am using uasort.
I recently answered this question in a much more capable manner in the "definitive" topic on sorting multidimensional arrays. You can safely skip reading the rest of this answer and directly follow the link for a much more capable solution.
uasortlets you define your own comparison function. Simply put all the criteria you want inside that.
For example, to sort by birthday and then by name:
I am ignoring the fact that in your example, the birthdays are not in a format that can be ordered by a simple comparison using the operator
<. In practice you would convert them to a trivially-comparable format first.
Update: if you think that maintaining a bunch of these multiple-criteria comparers could get ugly real fast, you find me in agreement. But this problem can be solved as any other in computer science: just add another level of abstraction.
I 'll be assuming PHP 5.3 for the next example, in order to use the convenient anon function syntax. But in principle, you could do the same with
You could then do:
This example possibly tries to be too clever; in general I don't like to use functions that do not accept their arguments by name. But in this case, the usage scenario is a very strong argument for being too clever.