PHP two-dimensional array sorting function

Source: Internet
Author: User

A PHP one-dimensional array can be sorted with functions such as sort (), Asort (), Arsort (), but the ordering of PHP's two-dimensional arrays needs to be customized.

The following function is to sort a given two-dimensional array according to the specified key value, and first look at the function definition:

functionArray_sort ($arr,$keys,$type= ' ASC '){     $keysvalue=$new _array=Array(); foreach($arr  as $k=$v){        $keysvalue[$k] =$v[$keys]; }    if($type= = ' ASC '){        Asort($keysvalue); }Else{        Arsort($keysvalue); }    Reset($keysvalue); foreach($keysvalue  as $k=$v){        $new _array[$k] =$arr[$k]; }    return $new _array; } 

It can sort the two-dimensional arrays by the specified key values, or you can specify ascending or descending sorting (the default is ascending), and the usage example:

$array=Array(    Array(' name ' = ' phone ', ' brand ' = ' Nokia ', ' Price ' =>1050),Array(' name ' = ' notebook computer ', ' brand ' = ' Lenovo ', ' Price ' =>4300),Array(' name ' = ' razor ', ' brand ' = ' Philips ', ' Price ' =>3100),Array(' name ' = = ' treadmill ', ' brand ' = ' three and ' pine stone ', ' price ' =>4900),Array(' name ' = ' watch ', ' brand ' = ' casio ', ' Price ' =>960),Array(' name ' = ' + ' LCD tv ', ' Brand ' = ' sony ', ' Price ' =>6299),Array(' name ' = ' laser printer ', ' brand ' = ' hp ', ' Price ' =>1200));$ShoppingList= Array_sort ($array, ' Price '); For $array, this two-dimensional array is sorted by ' price ' from low to highPrint_r($ShoppingList);

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.