PHP implements sorting of a key in a two-dimensional array. php two-dimensional array

Source: Internet
Author: User

PHP implements sorting of a key in a two-dimensional array. php two-dimensional array

This example describes how PHP sorts keys in a two-dimensional array. We will share this with you for your reference. The details are as follows:

/*** Sort the query result set * @ access public * @ param array $ list query result * @ param string $ field name * @ param string $ sortby sorting type (asc forward sorting desc reverse sorting nat natural sorting) * @ return array */function list_sort_by ($ list, $ field, $ sortby = 'asc ') {if (is_array ($ list )) {$ refer = $ resultSet = array (); foreach ($ list as $ I => $ data) {$ refer [$ I] = & $ data [$ field];} switch ($ sortby) {case 'asc ': // asort ($ refer); break; c Ase 'desc': // reverse sorting arsort ($ refer); break; case 'nat ': // natural sorting natcasesort ($ refer); break ;} foreach ($ refer as $ key => $ val) {$ resultSet [] = & $ list [$ key];} return $ resultSet;} return false ;} /*** example *: sort the IDs of two-dimensional arrays in descending order (that is, the bigger the IDs, the more advanced )? */$ List = array (0 => array ('id' => 1, 'name' => '1 '), 1 => array ('id' => 3, 'name' => '3'), 2 => array ('id' => 2, 'name' => '2'), 3 => array ('id' => 4, 'name' => '4 '),); // Answer $ new_list = list_sort_by ($ list, 'id', 'desc'); print_r ($ new_list );

The running result is as follows:

Array ([0] => Array ([id] => 4 [name] => fourth) [1] => Array ([id] => 3 [name] => third) [2] => Array ([id] => 2 [name] => second) [3] => Array ([id] => 1 [name] => first ))

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.