PHP Arrays
Sorting an Array Using a Method Instead of a Function
Problem
You want to define a custom sorting routine to order an array. However, instead of using a function, you want to use an object method.Solution
Pass in an array holding a class name and method in place of the function name:usort($access_times, array('dates', 'compare'));
Discussion
As with a custom sort function, the object method needs to take two input arguments and return 1, 0, or −1, depending on whether the first parameter is larger than, equal to, or less than the second:class sort {
// reverse-order string comparison
static function strrcmp($a, $b) {
return strcmp($b, $a);
}
}
usort($words, array('sort', 'strrcmp'));
It must also be declared as static. Alternatively, you can use an instantiated object:
class Dates {
public function compare($a, $b) { /* compare here */ }
}
$dates = new Dates;
usort($access_times, array($dates, 'compare'));
No comments:
Post a Comment