php usort

      No Comments on php usort

Array sorting is always fun.  php provides more functions then you can imagine to do array sorting.  I recently had to use the usort function.  It’s a pretty handy one for sorting single values on their keys so you can end up with apple in index 0 and zebra in index 21, or whatever the last index is.  The big key to it is it allows you to write the sort function yourself.

My task was to sort an array of alphanumberic strings by name and number.  For example, RCM23 goes before RCM121 and after RCR23.  Also, RCM23A needs to go after RCM23 but before RCM 33.  In comes usort, with a custom function to sort my array.

[sourcecode language=”php”]
usort($files, "arraySortCallback"); //You can name the function whatever you want. THe function returns either -1, 0, or 1 to indicate which of the two passed values is larger.

function arraySortCallback($a, $b) {
$txt1 = substr($a,0,3);
$txt2 = substr($b,0,3);
$num1 = (int) preg_replace("[D]", "", $a);
$num2 = (int) preg_replace("[D]", "", $b);
if($txt1 === $txt2) {
if($num1 === $num2) {
return $a > $b;
}
else {
return $num1 > $num2;
}
}
else {
return strcmp($txt1, $txt2) > 0;
}
};
[/sourcecode]

And with that, the sorts all worked out and products displayed correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *