Home  >  Article  >  类库下载  >  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

高洛峰
高洛峰Original
2016-10-09 11:51:171202browse

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 is true for multi-dimensional arrays Same idea.

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

Assuming that the flashback is based on price, we need to obtain the price field values, as a new one-dimensional array.

$arr1 = array_map(create_function('$n', 'return $n["price"];'), $data);

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

Then use array_multisort to process,

array_multisort($arr1,SORT_DESC,$data);//Sort of multi-dimensional arrays

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

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

Statement:
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

Related articles

See more