Home > Backend Development > PHP Tutorial > Detailed explanation of PHP multidimensional array sorting examples

Detailed explanation of PHP multidimensional array sorting examples

小云云
Release: 2023-03-22 20:40:01
Original
1482 people have browsed it

This article mainly shares with you detailed examples of PHP multi-dimensional array sorting, mainly in the form of text and code, hoping to help everyone.

思路:获取其中你需要排序的字段,作为一维数组 arr,后边会用来排序多维数组 data.
这里主要以二维数组为例,多维数组也是同样的思路。 

$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'),
);

假设以 price 来降序,我们就需要获取 price 这个字段的值,作为一个新的一维数组。
$arr = array_map(create_function('$n', 'return $n["price"];'), $data);

如果 php 版本大于 5.5 的话,可以直接用 array_column 这个数组操作方法直接获取某个字段,这里也可以通过 foreach 来获取,但是尽量用内置函数处理。

这里就用 array_multisort 处理多维数组的排序
array_multisort($arr, SORT_DESC, $data );

结果:
Copy after login
Copy after login

Detailed explanation of PHP multidimensional array sorting examples

思路:获取其中你需要排序的字段,作为一维数组 arr,后边会用来排序多维数组 data.
这里主要以二维数组为例,多维数组也是同样的思路。 

$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'),
);

假设以 price 来降序,我们就需要获取 price 这个字段的值,作为一个新的一维数组。
$arr = array_map(create_function('$n', 'return $n["price"];'), $data);

如果 php 版本大于 5.5 的话,可以直接用 array_column 这个数组操作方法直接获取某个字段,这里也可以通过 foreach 来获取,但是尽量用内置函数处理。

这里就用 array_multisort 处理多维数组的排序
array_multisort($arr, SORT_DESC, $data );

结果:
Copy after login
Copy after login

Detailed explanation of PHP multidimensional array sorting examples

Related recommendations:

php custom two-dimensional array sorting function array

Several PHP ways to sort two-dimensional arrays

PHP multi-dimensional array sorting algorithm analysis

The above is the detailed content of Detailed explanation of PHP multidimensional array sorting examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template