sorting an associated array
intro
so, lets say you’ve got an associative array that you want to sort, a simple sort() might not always suffice depending on the array architecture. if you have an array that looks something like the one below, and you want to sort by the timestamp, you will have hard time doing so with something like sort():
array (
1 => array (
[timestamp] => 123456789
[name] => "name"
[message] => "hi there"
)
2 => array (
[timestamp] => 123456987
[name] => "name2"
[message] => "hi yourself"
)
)
solution
php has a great function called uasort() that allows you to define your own sorting scheme for the data. so, you write a function, lets call it mySort(), and then use the uasort() to reference the mySort function as follows:
uasort($myArray, "mySort");
in the case of the array above, i would write a function to sort by the timestamp as follows:
function mySort($a, $b) {
if ($a["timestamp"] == $b["timestamp"]) return 0;
return ($a["timestamp"] > $b["timestamp"]) ? -1 : 1;
}
$a and $b represent the two items to be compared, in this case $myArray[0] and $myArray[1]. if the two timestamps are equal there is no need to make a position swap so 0 is returned (which means no swap is necessary), otherwise it returns a -1 or a 1 (move the item up or down) base on whether its greater than the next item or not. since there is no build in sort function in php to apply a sort to a value thats nested deep within an array, these types of sorts come in handy all the time.




