PHP Function Oret - Sorting Associative Data in PHP
php function usort is a useful function for sorting particular types of data that cannot be correctly sorted by PHP's normal array sorting functions. The usort() function uses a callback function to compare each element in an associative array by its value and then sorts the array based on the comparison result. The resulting order is different from the original order for each element.
It is very common for data to appear in associative array format. For example, data returned from database/SQL queries often appears in this format. In these situations it is usually necessary to sort the data based on one or more conditions, a task that is made very simple with the help of php's array_multisort() function.
For instance, the array below contains six records for a person (firstname, lastname and age). It would be useful to sort these records in the order that they are returned from the database, which means that we need to sort them by lastname followed by first name.
The above example uses the usort() function with a callback function to sort the person records by their age. The comparison function is implemented in a static class called PersonComparer which contains a compare() method that returns a strcmp(firstname, lastname, age) value for each of the people records in the array.
The usort() function will assign new keys for the elements in the array and remove any existing keys that may already have been assigned. The return value of the usort() function is TRUE if the function is called and FALSE otherwise.