PHP Two-dimensional arrays are sorted according to a field

Source: Internet
Author: User

Original: PHP two-dimensional array sorted by a field

Requirements: Fetch the respective 4 data from two different tables, then consolidate (Array_merge) into an array, then sort the first 4 according to the data creation time in descending order.

It is not an ORDER by problem that can be solved when this requirement is met. So look at the PHP manual to find the following method, make this note.

<?PHP/** * The two-dimensional array is sorted according to a field * function: Sort by user's age in reverse order * @author Ruxing.li*/Header(' content-type:text/html; Charset=utf-8 ');$arrUsers=Array(    Array(            ' id ' = 1, ' name ' = ' Zhang San ', ' age ' = 25,    ),Array(            ' id ' = 2, ' name ' = ' John Doe ', ' age ' = 23,    ),Array(            ' id ' = 3, ' name ' = ' Harry ', ' age ' = 40,    ),Array(            ' id ' = 4, ' name ' = ' Zhao Liu ', ' age ' = 31,    ),Array(            ' id ' = 5, ' name ' = ' Yellow seven ', ' age ' = 20,    ),); $sort=Array(        ' Direction ' = ' sort_desc ',//sort order flag Sort_desc descending; SORT_ASC Ascending' Field ' = ' age ',//Sort Fields);$arrSort=Array();foreach($arrUsers  as $uniqid=$row){    foreach($row  as $key=$value){        $arrSort[$key][$uniqid] =$value; }}if($sort[' Direction ']){    Array_multisort($arrSort[$sort[' Field '],constant($sort[' direction ']),$arrUsers);}Var_dump($arrUsers);/*output: Array (size=5) 0 = = Array (size=3) ' id ' + = int 5 ' name ' = = String ' Yellow Seven ' (length=6) ' A GE ' = = int 1 = array (size=3) ' id ' + = int 2 ' name ' = ' John Doe ' (length=6) ' Age ' =&G T  int 2 = = Array (size=3) ' id ' + int 1 ' name ' = = String ' Zhang San ' (length=6) ' age ' = int 25 3 = = Array (size=3) ' id ' = = int 4 ' name ' = = String ' Zhao Liu ' (length=6) ' age ' = int 4 =>     ; Array (size=3) ' id ' + = int 3 ' name ' + = String ' Harry ' (length=6) ' age ' = int*/

PHP Two-dimensional arrays are sorted according to a field

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.