Home > php教程 > php手册 > PHP multidimensional array sorted based on the value of one of the fields

PHP multidimensional array sorted based on the value of one of the fields

WBOY
Release: 2016-09-28 08:38:23
Original
1263 people have browsed it

Usually simple one-dimensional arrays or simple array sorting will not be introduced here. This is mainly for the situations that may be encountered in daily projects, sorting according to one of the multi-dimensional arrays.
The php function used is: array_multisort.

Idea: Get the field you need to sort as a one-dimensional array arr1, which will be used to sort the multi-dimensional array data later.
Here we mainly take a two-dimensional array as an example, and the same idea is used for multi-dimensional arrays.

$data = array(<br>    array('price' => '500', 'count' => '40', 'level' => '1'),<br>    array('price' => '600', 'count' => '30', 'level' => '2'),<br>    array('price' => '650', 'count' => '20', 'level' => '3'),<br>    array('price' => '700', 'count' => '10', 'level' => '4'),<br>);
Copy after login

Assuming that the flashback is based on 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);
Copy after login

If the PHP version is greater than 5.5, you can directly use the array_column array operation method to directly obtain a field. You can also obtain it through foreach, but try to use built-in functions to handle it.

Then use array_multisort to process,

array_multisort($arr1,SORT_DESC,$data );//多维数组的排序
Copy after login

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

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template