我有一个像这个例子这样的多维数组
$arr = array (
range(9,4),
range(8,0),
range(2,7),
range(-1,17)
);
显示其内容后我得到了这个
9 8 7 6 5 4
8 7 6 5 4 3 2 1 0
2 3 4 5 6 7
-1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
现在我想要得到的结果是这样的
-1 0 0 1 1 2
2 2 3 3 3 4 4 4 4
5 5 5 5 6 6
6 6 7 7 7 7 8 8 8 9 9 10 11 12 13 14 15 16 17
我定义了一个函数来对数组进行排序并返回我需要的结果,但我想知道是否有一种简单的方法可以使用预定义的函数或简单快速的算法来实现此目的
这是我的功能
function sort_multi($arr)
{
$length = 0;
foreach ($arr as $value)
$length += count($value);
$sorted = false;
while(!$sorted)
{
$x = 0;
$y = 0;
$sorted = true;
while(($x+$y)<($length-1) && isset($arr[$x][$y]))
{
$new_x = isset($arr[$x][$y+1])?$x:($x+1);
$new_y = isset($arr[$x][$y+1])?($y+1):0;
if(($new_x+$new_y)<$length && isset($arr[$new_x][$new_y]))
if($arr[$x][$y] > $arr[$new_x][$new_y])
{
perm($arr[$x][$y], $arr[$new_x][$new_y]);
$sorted=false;
}
$x = $new_x;
$y = $new_y;
}
}
return $arr;
}
perm
的定义是
function perm(&$a,&$b)
{
$inter = $a;
$a = $b;
$b = $inter;
}
最佳答案
我认为 array_walk_recursive 可以很好地处理这样的事情。
// Fill a temp array with all the values from the multidimensional array...
$temp = array();
array_walk_recursive($arr, function($item) use (&$temp) {
$temp[] = $item;
});
sort($temp); // sort it...
// refill the multidimensional array with the sorted values.
array_walk_recursive($arr, function(&$item) use (&$temp) {
$item = array_shift($temp);
});
关于php - 对多维数组进行排序的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24936208/