For example, an array like the following:
Copy code The code is as follows:
$users = array(
array('name' => 'tom ', 'age' => 20)
, array('name' => 'anny', 'age' => 18)
, array('name' => 'jack', 'age' => 22)
);
I hope I can sort them by age from small to large. The author has sorted out two methods and shared them with you.
1. Use array_multisort
Using this method, it will be more troublesome. You need to extract the age and store it in a one-dimensional array, and then arrange it in ascending order by age. The specific code is as follows:
Copy code The code is as follows:
$ages = array();
foreach ($users as $user) {
$ages[] = $user['age'];
}
array_multisort($ages, SORT_ASC, $users);
After execution, $users is a sorted array, which can be printed out to see. If you need to sort by age in ascending order first, and then by name in ascending order, the method is the same as above, that is, extract an additional name array. The final sorting method is called like this:
Copy code The 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 more complex sorting methods. For example, sort in descending order by name length:
Copy code The code is as follows:
usort($users, function($a, $b) {
$ al = strlen ($a['name']); > return ($al > $bl) ? -1 : 1;
});
Anonymous functions are used here and can be extracted separately if necessary. Among them, $a and $b can be understood as elements under the $users array. You can directly index the name value, calculate the length, and then compare the lengths.
The author prefers the second method because it eliminates the step of extracting the sorted content into a one-dimensional array and the sorting method is more flexible.
http://www.bkjia.com/PHPjc/621652.html
www.bkjia.com
truehttp: //www.bkjia.com/PHPjc/621652.htmlTechArticleFor example, an array like the following: Copy the code The code is as follows: $users = array( array('name' = 'tom ', 'age' = 20) , array('name' = 'anny', 'age' = 18) , array('name' = 'jack', 'age' = 22) )...