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 :)

Friday, October 27, 2006

Performancing testing

When i blog in my php blog i plan to use the firefox extention performancing. I have heard much praise about it so i look forward to seeing how well i like it. I will keep the blog informed about my progress with it.

Another option for me as a vim user is to find some console program that use vim to blog with. I will look into that as well, if anybody have a tip about such a program please let me know in the comments or on IRC.

meus out.

Started new php blog

I just started this blog to rant about random findings and experiences i have when developing php stuff. I hang out at #phpc on freenode as meus (that is why i called the blog meus on php) so if you want to say hi please join the channel and become a part of this nice community.

meus out.