The ksort function is perhaps most useful in situations where you have an associative
array and you don't have complete control over the contents. In Listing 15.6 the script
gets an array generated by the getdate function. If you run it with the ksort line
commented out, you will see that the order is arbitrary. It's simply the order chosen when
the function was coded. I could have typed a couple lines for each element based on the
list of elements found in the description of the getdate function in Chapter 11,
"Time, Date, and Configuration Functions." A more readable solution is to sort
on the keys and to print each element in a loop. As you might have guessed, the krsort
function sorts an array by its indices in reverse.
Sorting with a Comparison Function
The built-in sorting functions are appropriate in the overwhelming majority of situations.
If your problem requires a sort that performs better than the one used in the built-in
functions, you are faced with coding your own. If your problem is that you need to
compare complex elements, such as objects or multidimensional arrays, the solution is to
write a comparison function and plug it into the usort function.
The usort function allows you to sort an array using your own comparison function.
Your comparison function must accept two values and return an integer. The two
arguments are compared, and if a negative number is returned, then the values are
considered to be in order. If zero is returned, they are considered to be equal. A positive
number signifies that the numbers are out of order.
In Listing 15.7 I've created a multidimensional array with three elements: name, title,
and wage. Sometimes I want to be able list employees by name, but other times I might
want to list them by title or how much they make per hour. To solve this problem, I've
written three comparison functions.
The byName function is a simple wrapper for strcmp. Names will be ordered by ASCII
code. The byTitle function assigns an integer value to each title and then returns the
comparison of these integers. The bySalary function compares the wage element, but
if two employees make the same amount of money per hour, their names are compared.
Listing 15.7 Using the usort Function