PHP array object custom sorting

Source: Internet
Author: User
PHP array object custom sorting recently encountered a problem:

Multiple fields are sorted by the next array object (that is, the elements of the array are objects containing multiple fields). The original data of the array object is as follows:

The sorting rules are as follows:

1 The createtime field of the object is sorted in ascending order by default.

2. when the creation time is equal, values are sorted in ascending order.

According to the above sorting rules, the final display result should be:

Data [2]-> Data [3]-> Data [0]-> Data [1]

Now, PHP comes with the sorting method. The simple sorting (sort) can only be sorted in alphabetical order according to the key values of a field, for example, after sorting the preceding array object data by sort, the displayed results are:

Sort ($ data );


Here we can see that sort is sorted in ascending order by default according to the paracode key value of the first field in the data array, which is not what I want.

So far, the sorting I need is complicated and I can only consider custom sorting.

PHP allows you to define your own sorting algorithm. you can create your own comparison function and pass it to the usort () function to create custom sorting. For a user-defined comparison function, if the first parameter is smaller than the second parameter, the comparison function must return a number smaller than 0, and vice versa, a number larger than 0, if the two parameters are equal, 0 is returned. The custom sorting format is as follows:

Usort (array to be sorted, 'user-defined sorting function name ');

For example, to sort the length of elements in the array data, execute the PHP program as follows:

Now back to the original question, according to my needs, the custom PHP sorting function is as follows:

The sorting result is as follows:


It can be seen that when the createtime is equal, paracode is arranged in ascending order, which is exactly the result I need.

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.