PHP multi-dimensional arrays are sorted by the values of one field, and php multi-dimensional arrays are sorted.

Source: Internet
Author: User

PHP multi-dimensional arrays are sorted by the values of one field, and php multi-dimensional arrays are sorted.

In normal times, simple one-dimensional arrays or simple array sorting are not described here. This is mainly used to sort projects based on one of the multi-dimensional arrays.
The php function used is: array_multisort.

Train of Thought: Get the fields you need to sort as one-dimensional array arr1, which will be used later to sort multi-dimensional array data.
Here we mainly use two-dimensional arrays as an example. Multi-dimensional arrays also share the same idea.

$ Data = array (
Array ('price' => '123', 'Count' => '40', 'level' => '1 '),
Array ('price' => '000000', 'Count' => '30', 'level' => '2 '),
Array ('price' => '123', 'Count' => '20', 'level' => '3 '),
Array ('price' => '123', 'Count' => '10', 'level' => '4 '),
);

For example, to reverse the price, we need to obtain the value of the price field as a new one-dimensional array.

$ Arr1 = array_map (create_function ('$ n', 'Return $ n ["price"];'), $ data );

If the php version is later than 5.5, you can directly use the Array Operation Method array_column to directly obtain a field. Here you can also use foreach to obtain the field, but try to use built-in functions for processing.

Then array_multisort is used for processing,

Array_multisort ($ arr1, SORT_DESC, $ data); // sorts multidimensional arrays.

We can print the final result of $ data to see the result:

 

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.