有时候需要对一个二维数组进行排序,自定义对应的排序规则,比如对一个班级里面的同学,先按身高降序排序,身高相同的,再按体重降序排序。。。
代码:
<?php $array = [ ["id" => "1", "name" => "a", "age" => "19",], ["id" => "2", "name" => "b", "age" => "39",], ["id" => "3", "name" => "c", "age" => "9",], ["id" => "4", "name" => "d", "age" => "1",], ["id" => "5", "name" => "e", "age" => "88",], ["id" => "6", "name" => "f", "age" => "65",], ["id" => "7", "name" => "g", "age" => "19",], ]; array_multisort(array_column($array,"age"),SORT_DESC,array_column($array,"id"),SORT_DESC,$array); print_r($array); ?>
上面这个二维数组,先按年龄(age)降序排序,如果年龄(age)相同的话,再按 id 降序排序
输出:
Array ( [0] => Array ( [id] => 5 [name] => e [age] => 88 ) [1] => Array ( [id] => 6 [name] => f [age] => 65 ) [2] => Array ( [id] => 2 [name] => b [age] => 39 ) [3] => Array ( [id] => 7 [name] => g [age] => 19 ) [4] => Array ( [id] => 1 [name] => a [age] => 19 ) [5] => Array ( [id] => 3 [name] => c [age] => 9 ) [6] => Array ( [id] => 4 [name] => d [age] => 1 ) )
原文地址:https://www.cnblogs.com/lyc94620/p/9973143.html
时间: 2024-11-09 23:21:12