php usort
Tuesday 02/10/2009 – Category: Uncategorized
I learned about a nifty PHP function that allows you to sort an array with a user-defined comparison function. This is useful if you have an array of database results and need to sort by one element in the result array (normally it would be better to sort with the SQL query but I had a mixed dataset to sort).
This is a bit similar to ranges in Ruby where the objects you're comparing have to be comparable with the <=> operator.
Sample usort with custom function:
function cmp($a, $b) { if($a["view_order"] == $b["view_order"]) return 0; else if($a["view_order"] > $b["view_order"]) return 1; else if($a["view_order"] < $b["view_order"]) return -1; } usort($tab_items, "cmp");
2 Responses to “php usort”
Leave a Reply
Recent Posts
- Good Word - now with definitions!
(Friday 03/5/2010 – 2 Comments) - Good Word - Words With Friends Word Checker
(Thursday 02/25/2010 – 31 Comments) - Facebook App Development gotchas
(Friday 02/19/2010 – No Comments) - StoreKit SKErrorUnknown
(Friday 02/19/2010 – 1 Comment)

April 11th, 2009 at 2:46 am
You know, you could just do two checks and return
May 12th, 2009 at 9:40 pm
you are very correct…it helps having readable code though