4.17. Sorting an Array by a Computable Field
Problem
You want to define your own sorting routine.
Solution
Use usort( )
in combination with a custom
comparison function:
// sort in reverse natural order
function natrsort($a, $b) {
return strnatcmp($b, $a);
}
$tests = array('test1.php', 'test10.php', 'test11.php', 'test2.php');
usort($tests, 'natrsort');Discussion
The comparison function must return a value greater that 0 if
$a > $b, 0 if $a == $b, and a value less than 0 if $a < $b. To sort in reverse, do the opposite. The function in
the Solution, strnatcmp( )
,
obeys those rules.
To reverse the sort, instead of multiplying the return value of
strnatcmp($a, $b) by -1, switch
the order of the arguments to strnatcmp($b, $a).
The sort function doesn’t need to be a wrapper for
an existing sort. For instance, the pc_date_sort( )
function, shown in Example 4-2, shows how to sort dates.
Example 4-2. pc_date_sort( )
// expects dates in the form of "MM/DD/YYYY"
function pc_date_sort($a, $b) {
list($a_month, $a_day, $a_year) = explode('/', $a);
list($b_month, $b_day, $b_year) = explode('/', $b);
if ($a_year > $b_year ) return 1;
if ($a_year < $b_year ) return -1;
if ($a_month > $b_month) return 1;
if ($a_month < $b_month) return -1;
if ($a_day > $b_day ) return 1;
if ($a_day < $b_day ) return -1;
return 0;
}
$dates = array('12/14/2000', '08/10/2001', '08/07/1999');
usort($dates, 'pc_date_sort');While sorting, usort( ) frequently recomputes the sort function’s return values each time it’s ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access