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.