Get the App
SLTechnology News&Howtos  ›  Development  › 

Sorting method of php two-dimensional array

Shulou Source: shulou.com Published: 2022-06-03 15:42:42 10月05日 Update

This article mainly talks about "the sorting method of php two-dimensional array". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "the sorting method of php two-dimensional array"!

The copy code is as follows:

$users = array (

Array ('name' = >' tom', 'age' = > 20)

, array ('name' = >' anny', 'age' = > 18)

, array ('name' = >' jack', 'age' = > 22)

);

I want to be able to sort by age from small to big. The author sorted out two methods and shared them with you.

1. Use array_multisort

Using this method, it is more troublesome to extract the age and store it in an one-dimensional array, and then sort it in ascending order of age. The specific code is as follows:

The copy code is as follows:

$ages = array ()

Foreach ($users as $user) {

$ages [] = $user ['age']

}

Array_multisort ($ages, SORT_ASC, $users)

After execution, $users is the sorted array, which can be printed out. If you need to sort by age ascending order, and then by name ascending order, the method is the same as above, it is to extract one more name array, and the final sorting method is called like this:

The copy code is as follows:

Array_multisort ($ages, SORT_ASC, $names, SORT_ASC, $users)

2. Use usort

The biggest advantage of using this method is that you can customize some of the more complex sorting methods. For example, sort in descending order by the length of the name:

The copy code is as follows:

Usort ($users, function ($a, $b) {

$al = strlen ($a ['name'])

$bl = strlen ($b ['name'])

If ($al = = $bl)

Return 0

Return ($al > $bl)?-1: 1

});

Anonymous functions are used here, which can be extracted separately if necessary. Where $a, $b can be understood as the elements under the $users array, you can directly index the name value, calculate the length, and then compare the length.

The author prefers the second method because there are fewer steps to extract the sorted content into an one-dimensional array, and the sorting method is more flexible.

At this point, I believe that you have a deeper understanding of "the sorting method of php two-dimensional array". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Method sort code array two-dimensional content ascending order name that is length author one-dimensional learning complex practical deeper maximum from small to big two from small to small Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Microsoft macOS Docker Xiaomi