The sorting problem of PHP multidimensional array

Source: Internet
Author: User

Arrays have very powerful features and flexibility and are widely used in PHP. PHP provides a number of sorting functions for one-dimensional arrays, such as sort (), Ksort (), and so on, using them to easily sort a one-dimensional array. But it cannot be used for two-dimensional array ordering, but we can use PHP provided by Usort (), Uasort (), Uksort () and other functions for two-dimensional sorting.

Use Usort () to sort one-dimensional arrays:

function My_sort ($a, $b) {if ($a = = $b) return 0;return ($a < $b)? -1:1;} $a =array (4,2,8,6); usort($a,"my_sort")

The Usort () function is sorted by a user-defined comparison function, but the keyword is not saved.
Uasort () will save the keyword.
Uksort () sorting will be based on keywords

Use Usort () to sort two-dimensional arrays:
$students = Array (
[' Name ' = ' Lili ', ' grade ' = ' 35 '),

2 = = Array (' name ' = ' Zhangsan ', ' grade ' = ' 95 '),
3 = = Array (' name ' = ' Wangwu ', ' grade ' = ' 88 ')
);

function Name_sort ($x, $y) {
return strcasecmp ($x [' name '], $y [' name ']);
}

function Grade_sort ($x, $y) {
return $x [' Grade '] < $y [' grade '];
}

Uasort ($students, ' name_sort ');






















The sorting problem of PHP multidimensional array

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.