How to sort two-dimensional arrays in php: two-dimensional array sorting _ PHP Tutorial

Source: Internet
Author: User
A detailed explanation of the two-dimensional array sorting problem in php, two-dimensional array sorting. For details about the two-dimensional array sorting problem in php, two-dimensional array sorting in PHP, you can use the PHP built-in function uasort () Example 1: detailed explanation of the two-dimensional array sorting problem in php using the user-defined comparison function logarithm, two-dimensional array sorting

For sorting two-dimensional arrays in PHP, you can use the PHP built-in function uasort ()

Example 1:

Sort the values in the array using the user-defined comparison function and maintain the index Association

The callback function is as follows: when the return value of the callback function is negative or false, it indicates that the first parameter of the callback function is placed before and the second parameter is arranged after.

$ Person = array ('num' => '001', 'id' => 6, 'name' => 'hangsan ', 'age' => 21 ), array ('num' => '001', 'id' => 7, 'name' => 'ahangsan', 'age' => 23 ), array ('num' => '003 ', 'id' => 1, 'name' => 'bhangsan', 'age' => 23 ), array ('num' => '001', 'id' => 3, 'name' => 'dhangsan', 'age' => 23 ),); // negative or false indicates that the first parameter should be in the previous function sort_by_name ($ x, $ y) {return strcasecmp ($ x ['name'], $ y ['name']);}

Use:

uasort($person,'sort_by_name');

The following provides a two-dimensional array sorting method for reference and interview:

// $ Array the array to be sorted // $ row sort by column // $ type [asc or desc] // return the sorted array function array_sort ($ array, $ row, $ type) {$ array_temp = array (); foreach ($ array as $ v) {$ array_temp [$ v [$ row] = $ v ;} if ($ type = 'asc ') {ksort ($ array_temp);} elseif ($ type = 'desc') {krsort ($ array_temp );} else {} return $ array_temp ;}

Example 2:

To sort one-dimensional arrays, you can use asort, ksort, and other methods to sort processes, which is relatively simple. How can we sort two-dimensional arrays? Use array_multisort and usort to implement

For example, the following array:

The code is as follows:

$users = array(  array('name' => 'tom', 'age' => 20)  , array('name' => 'anny', 'age' => 18)  , array('name' => 'jack', 'age' => 22));

We hope to sort data by age size from small to large. I have sorted out two methods and shared them with you.

1. use array_multisort

Using this method will be more troublesome. you need to extract the age and store it in a one-dimensional array, and then sort it in ascending order by age. The code is as follows:

The 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. you can print it out. If you want to sort by age in ascending order and then by name in ascending order, the method is the same as above, that is, to extract an array of names. The final sorting method is called as follows:

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 complicated sorting methods. For example, sort by name length in descending order:

The 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;    });

The anonymous function is used here. if necessary, it can be extracted separately. $ A and $ B can be understood as elements in the $ users array. you can directly index the name value, calculate the length, and then compare the length.

========================================================== ==================================

By the way, several PHP sorting functions

Sort sorts arraysIt is applicable to one-dimensional index arrays without indexes.

Rsort sorts arrays in reverse orderConsistent with sort usage

Asort sorts arraysAnd keep the index relationship to sort the values. it is generally applicable to one-dimensional arrays and maintains the index relationship.

Arsort sorts arrays in reverse order and maintains the index relationship.Consistent with asort usage

Ksort sorts arrays by key names

Krsort sorts arrays in reverse order by key name

For sorting two-dimensional arrays in PHP, you can use the PHP built-in function uasort (). Example 1: use the user-defined logarithm of the comparison function...

Related Article

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.