Recipe 4.19. Sorting an Array Using a Method Instead of a Function


4.19.1. 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.

4.19.2. Solution

Pass in an array holding a class name and method in place of the function name:

usort($access_times, array('dates', 'compare'));

4.19.3. Discussion

As with a custom sort function, the object method needs to take two input arguments and return 1, 0, or -1, depending if the first parameter is larger than, equal to, or less than the second:

class pc_sort {     // reverse-order string comparison     function strrcmp($a, $b) {         return strcmp($b, $a);     } } usort($words, array('pc_sort', 'strrcmp'));

4.19.4. See Also

Chapter 7 for more on classes and objects; Recipe 4.17 for more on custom sorting of arrays.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net