Home > Backend Development > PHP Tutorial > PHP sorts according to a certain field in the array

PHP sorts according to a certain field in the array

王林
Release: 2023-04-08 08:54:02
forward
9987 people have browsed it

PHP sorts according to a certain field in the array

Function introduction:

array_multisort() function returns a sorted array. You can enter one or more arrays. The function sorts the first array first, then the other arrays, and if two or more values ​​are the same, it sorts the next array.

Code example:

1. Sort by single field:

$data = [
    ['id' => 1, 'name' => '张三', 'sort' => 60],
    ['id' => 2, 'name' => '李四', 'sort' => 40],
    ['id' => 3, 'name' => '王五', 'sort' => 80],
];

// 先取出要排序的字段的值
$sort = array_column($data, 'sort');
// 按照sort字段升序  其中SORT_ASC表示升序 SORT_DESC表示降序
array_multisort($sort, SORT_ASC, $data);
// 输出结果
var_dump($data);
Copy after login

Related learning video tutorial sharing: php video tutorial

2 , Sorting by multiple fields:

$data = [
    ['id' => 1, 'name' => '张三', 'sort' => 60],
    ['id' => 2, 'name' => '李四', 'sort' => 60],
    ['id' => 3, 'name' => '王五', 'sort' => 80],
];

// 先取出要排序的字段的值
$sort = array_column($data, 'sort');
$name = array_column($data, 'name');
// 先按照sort字段升序,再按照name字段降序
array_multisort($sort, SORT_ASC, $name, SORT_DESC, $data);
// 输出结果
var_dump($data);
Copy after login

Recommended related articles and tutorials: php tutorial

The above is the detailed content of PHP sorts according to a certain field in the array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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