duanjue2576 2014-07-24 14:16
浏览 31
已采纳

排序多维数组的最佳方法

I have a multidimentionnal array like this example

$arr = array (
      range(9,4),
      range(8,0),
      range(2,7),
      range(-1,17)
   );

after showing its content I get this

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 

Now the result I want to get is this

-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

I defined a function that sorts the array and returns the result I need, but I want to know if there is a simple way to do it using predefined functions or a simple and fast algorithm

this is my function

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;
}

the definition of perm is

function perm(&$a,&$b)
{
   $inter = $a;
   $a = $b;
   $b = $inter;
}
  • 写回答

3条回答 默认 最新

  • douhaodang0403 2014-07-24 14:38
    关注

    I don't know which is the best way. But you can do it brute force: Sample Output

    $arr = array (
        range(9,4),
        range(8,0),
        range(2,7),
        range(-1,17),
    );
    
    // simple checking of number of items per batch (since this is sort of like array_chunk, but jagged)
    $chunks = array_map(function($batch){ return count($batch); }, $arr);
    foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($arr)) as $v) {
        $values[] = $v; // simple flattening
    }
    sort($values); // sort ascending (prepping)
    foreach($chunks as $key => $batch) {
        // number of items in a batch
        // simple cutting (i can't find the function for this, i think there is)
        for($x = 0; $x < $batch; $x++) {
            $final[$key][] = $values[$x];
            unset($values[$x]);
        }
        $values = array_values($values); // reindex again (resetter)
    }
    
    echo '<pre>';
    print_r($final);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'