Sorting Array Keys in Reverse Order
The krsort() function operates identically to ksort(), sorting by key, except that it
sorts in reverse (descending) order. Its prototype follows:
integer krsort(array array [, int sort_flags])
Sorting According to User-Defined Criteria
The usort() function offers a means for sorting an array by using a user-defined
comparison algorithm, embodied within a function. This is useful when you need to
sort data in a fashion not offered by one of PHP??™s built-in sorting functions. Its prototype
follows:
void usort(array array, callback function_name)
The user-defined function must take as input two arguments and must return a negative
integer, zero, or a positive integer, respectively, based on whether the first argument
is less than, equal to, or greater than the second argument. Not surprisingly, this function
must be made available to the same scope in which usort() is being called.
A particularly applicable example of where usort() comes in handy involves the
ordering of American-format dates (month, day, year, as opposed to day, month, year
used by most other countries). Suppose that you want to sort an array of dates in
ascending order. While you might think the sort() or natsort() functions are suitable
for the job, as it turns out, both produce undesirable results. The only recourse is to create
a custom function capable of sorting these dates in the correct ordering:
152 CHAPTER 5 ?– ARRAYS
$dates = array('10-10-2003', '2-17-2002', '2-16-2003',
'1-01-2005', '10-10-2004');
sort($dates);
echo "
Sorting the array using the sort() function:
";
print_r($dates);
natsort($dates);
echo "
Sorting the array using the natsort() function:
";
print_r($dates);
function DateSort($a, $b) {
// If the dates are equal, do nothing.
Pages:
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232