Monday, October 30, 2006

Sorting with usaort

Problem: You have an array of objects or a multidimentional arrays where the key of the first array has some meaning. It could be a id or something else. You want to sort the array and maintain the key=>value association.

Some may then proceed to loop the array and sort it in a loop, however there is a easier method.

Sollution: Enters the php function Uasort. This function takes an array as the first argument and the name of a comparison function as a string. If you want to use a static method in a class you can use array("ClassName", "staticFuncName"). The user comparison function takes two arguments that correspond to two elements in your array. Do some comparison on them and return 0, -1 or 1 to adjust how you want them sorted. The function takes care of looping all elements and applying the comparison func correctly.

$testArray = array(
"testing3" => array("timestamp" => 11220022,
"name" =>"testing3"),
"testing" => array("timestamp" => 11220011,
"name" =>"testing"),
"testing2" => array("timestamp" => 11220033,
"name" =>"testing2"));

uasort($testArray, "sortTimestamp");
print_r($testArray);

function sortTimestamp($foo, $bar){
if($foo["timestamp"] == $bar["timestamp"]){
return 0;
}else if($foo["timestamp"] > $bar["timestamp"]){
return 1;
}else{
return -1;
}
}


This code outputs:

Array
(
[testing] => Array
(
[timestamp] => 11220011
[name] => testing
)

[testing3] => Array
(
[timestamp] => 11220022
[name] => testing3
)

[testing2] => Array
(
[timestamp] => 11220033
[name] => testing2
)

)


Now that is rather neat if you ask me :)

1 comment:

Oliver Nassar said...

Helped out amazingly. Thanks.