How to use the PHP function usort () to implement custom sorting _ PHP Tutorial

Source: Internet
Author: User
Use the PHP function usort () to implement custom sorting. There are many ways to sort arrays in, including sorting by value, by keyword, and by natural language. Today, we want to teach you how to use the PHP function usort () to sort arrays in multiple ways, 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:

 
 
  1. php
  2. $data = array("joe@host.com", "john.doe@gh.co.uk",
    "asmithsonian@us.info", "jay@zoo.tw");usort($data, 'sortByLen');
  3. print_r($data); function sortByLen($a, $b) {
  4. if (strlen($a) == strlen($b)) {
  5. return 0;
  6. } else {
  7. return (strlen($a) > strlen($b)) ? 1 : -1;
  8. }
  9. }
  10. ?>

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.


Bytes. What we want to teach you today is to use the PHP function usort () to implement it...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.