Home>Article>Backend Development> How to use array_multisort function in PHP to sort an array by specified fields

How to use array_multisort function in PHP to sort an array by specified fields

醉折花枝作酒筹
醉折花枝作酒筹 forward
2021-06-25 16:09:03 2960browse

There are some functions in PHP that can be used to sort arrays. But for an array with multiple fields, how to sort by specified fields? You can use the array_multisort function to sort by specified fields.

How to use array_multisort function in PHP to sort an array by specified fields

There are some functions in PHP that can be used to sort arrays.

  • sort() - Sort the array in ascending order

  • rsort() - Sort the array in descending order

  • asort() - Sort an array in ascending order based on the values of the associative array

  • ksort() - Sort the array in ascending order based on the keys of the associative array

  • arsort() - Sort an array in descending order based on the values of an associative array

  • krsort() - Sort an array in descending order based on the keys of an associative array

For example:

$arr=['green','car','apple','book']; sort($arr); var_dump($arr);

You can get the sorting result:

array (size=4) 0 => string 'apple' (length=5) 1 => string 'book' (length=4) 2 => string 'car' (length=3) 3 => string 'green' (length=5)

But for an array with multiple fields, how to sort according to the specified field What? For example, the following array:

$arr=[ [ 'age'=>50, 'name'=>'张三' ], [ 'age'=>18, 'name'=>'李四' ], [ 'age'=>27, 'name'=>'王五' ] ];

How do we sort by age or name? We can use the array_multisort function to sort by specified fields.

array_multisort(array_column($arr,'age'),SORT_ASC,$arr); var_dump($arr);

Print results

array (size=3) 0 => array (size=2) 'age' => int 18 'name' => string '李四' (length=6) 1 => array (size=2) 'age' => int 27 'name' => string '王五' (length=6) 2 => array (size=2) 'age' => int 50 'name' => string '张三' (length=6)

This way, it is sorted. That is to say, when sorting using the array_multisort function, use array_column to sort the column specified by the array to extract the first parameter and put the sorting constant If you put the second parameter and the array into the third parameter, you can sort by the specified field. SORT_ASC is ascending order, SORT_DESC is descending order.

Recommended learning:php video tutorial

The above is the detailed content of How to use array_multisort function in PHP to sort an array by specified fields. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete