多维数组排序
- php内置函数array_multisort()可以对多维数组排序
echo '<pre>';
$arr = [[34,12,[4,2],03],['b','a','c'],123,23];
array_multisort($arr);
print_r($arr);
运行结果如下:
Array
(
[0] => 23
[1] => 123
[2] => Array
(
[0] => b
[1] => a
[2] => c
)
[3] => Array
(
[0] => 34
[1] => 12
[2] => Array
(
[0] => 4
[1] => 2
)
[3] => 3
)
)
观察运行结果,只是对最外层的元素进行了排序,数组元素没有排序
- 下面使用递归思想实现多维数组排序
echo '<pre>';
$arr = [[34,12,[4,2],03],['b','a','c'],123,23];
function test($arr){
$arr1 = [];
foreach ($arr as $k=>$v){
if(is_string($v)|| is_int($v)){
array_push($arr1,$v);
}else{
array_push($arr1,test($v));
}
sort($arr1);
}
return $arr1;
}
print_r(test($arr));
运行结果:
Array
(
[0] => 23
[1] => 123
[2] => Array
(
[0] => a
[1] => b
[2] => c
)
[3] => Array
(
[0] => 3
[1] => 12
[2] => 34
[3] => Array
(
[0] => 2
[1] => 4
)
)
)