There are many ways to sort arrays in, including sorting by value, by keyword, and by natural language. What we want to teach you today is to use the PHP function usort () to sort custom arrays. You can create your own comparison function and pass it to the PHP function usort (). If the first parameter is "smaller" than the second parameter, the comparison function must return a number smaller than 0. If the first parameter is greater than the second parameter, the comparison function should return a number greater than 0.
Listing I is an example of the PHP function usort (). In this example, array elements are sorted based on their length, and the shortest items are placed at the beginning:
- <?php
- $data = array("joe@host.com", "john.doe@gh.co.uk",
"asmithsonian@us.info", "jay@zoo.tw");usort($data, 'sortByLen');
- print_r($data); function sortByLen($a, $b) {
- if (strlen($a) == strlen($b)) {
- return 0;
- } else {
- return (strlen($a) > strlen($b)) ? 1 : -1;
- }
- }
- ?>
In this way, we have created our own comparison function, which uses the PHP function usort () to compare the number of each string, and then returns 1, 0 or-1 respectively. the returned value is the basis for determining the arrangement of elements. The output result is as follows:
Array ([0] => jay@zoo.tw
Joe@host.com
John.doe@gh.co.uk
Asmithsonian@us.info
)
We hope that you can use this sample code to learn how to use the PHP function usort.