php - 对多维数组进行排序的最佳方法

标签 php arrays algorithm multidimensional-array

我有一个像这个例子这样的多维数组

$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/

相关文章:

javascript - React-Native fetch 不将正文内容发送到 $_POST

php - 通过 PHP 调用 ffmpeg 但不要等待

algorithm - 多维数组之和

php - 我在检查服务器状态时遇到一些问题

php - 如何将包含数字和空格的字符串转换为 int

python - 在 PyTorch 中将张量向量化分配给切片

java - 将 java 字节数组转换为字符串

javascript - 如果键存在,则使用键和值形成 JSON

java - 使用 HashMap 的字数统计程序

验证非相交形状的自由多边形顶点的算法