Array_multisort to sort associative arrays PHP

Source: Internet
Author: User

We often use arrays for sorting in the array operations of PHP, which is about sorting associative arrays
You need to use the function Array_multisort.
Array_multisort (Array_column ($arr, ' weight '), Sort_numeric, SORT_ASC, $arr);  convert key Column ' weight ' to numbers in ascending order for associative array $arr
Sort_numeric  //Convert to digital sorting
Sort_string  //Convert to text sorting
SORT_ASC     //Ascending
Sort_desc    //Descending

Example:
Original Associative array:
$data [] = Array (' volume ' = ' id100343 ', ' weight ' = ' 4 ');
$data [] = Array (' volume ' = ' id100212 ', ' weight ' = ' 1 ');
$data [] = Array (' volume ' = ' id104104 ', 'weight ' = ' 10 ');
Var_dump ($data);

Sort by weight (digital sort_numeric):


Output Result:
Array (3) {  [0]=>  Array (2) {    ["Volume"]=>    string (8) "id100212"    [" Weight "]=> string (1)" 1 " } [1]=> Array (2) { [" volume "]=> string (8)" id100343 " ["Weight"]=> string (1) "4" } [2]=> Array (2) { ["volume"]=> string (8) " id104104 " [" Weight "]=> string (2)" Ten " }}        
Sort by weight (text mode sort_string):
Array (3) {  [0]=>  Array (2) {    ["Volume"]=>    string (8) "id100212"    [" Weight "]=> string (1)" 1 " } [1]=> Array (2) { [" volume "]=> string (8)" id104104 " ["Weight"]=> string (2) "Ten" } [2]=> Array (2) { ["volume"]=> string (8) " id100343 " [" Weight "]=> string (1)" 4 " }}        

It is important to note that 10 is the difference between numbers and text.

Array_multisort to sort associative arrays 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.