Home>Article>Backend Development> 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);
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);
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!