About multidimensional array sorting in PHP

Source: Internet
Author: User

Problems with multidimensional array sorting are often encountered in the work, but different people do not handle the same method, such as the following array

$data = array(

        array("name"=>"kivmi","age"=>27),

        array("name"=>"sathen","age"=>24),

        array("name"=>"nancy","age"=>26),

        array("name")=>"du","age"=>23)

  )

  如果需要对$data按照age升级排序,该怎么处理呢?

  有些人,可能会先遍历数组,然后把age作为key,然后ksort来排序,或者直接取出age作为数组,并将索引作为key,然后对age使用asort排序,

  但是其实php提供了一个内置函数,来解决多维数组排序的问题,这就说明其对php手册不是很熟,php手册中有一个函数,array_mutilsort,其函数原型如下

  bool array_mutilsort(array &array1 [,mixed $array1_sort_order=SORT_DESC [,mixed $array1_sort_flags=SORT_REGULAR [,mixed...]]])

  这样就可以利用这个函数进行排序了,只需要将需要排序的字段值保存在一个数组中,并且能对多个字段进行排序,

  foreach($data as $key => $item){

    $ages[$key] = $item[‘age‘];

  }

Array_mutilsort ($ages, Sort_desc, $data);

This is a good order, simple, this problem has been done for 5 of years PHP programmers do not know that there is such a function, so we have to look at the manual.


 

 

About multidimensional array sorting in PHP

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.