方法封装:
if (!function_exists('sort_for_arrays')) {
/**
* 二维数组根据某个字段排序
* @param array $array 要排序的数组
* @param string $key 要排序的键字段
* @param string $sort 排序类型 SORT_ASC SORT_DESC
* @return array 排序后的数组
*/
function sort_for_arrays($array, $key, $sort = SORT_DESC)
{
$keys = array_column($array,$key);
array_multisort($keys, $sort, $array);
return $array;
}
}
测试:
$before_arrs = [
["id" => 2,"name" => "bbb"],
["id" => 1,"name" => "aaa"],
["id" => 3,"name" => "ccc"],
];
$after_arrs = sort_for_arrays($before_arrs,"id");
?>
<script type="text/javascript">
console.log("分组前:",<?php echo json_encode($before_arrs); ?>)
console.log("分组后:",<?php echo json_encode($after_arrs); ?>)
</script>
结果: