如何遍历这个三维数组

时间:2018-04-03 23:09:23

标签: arrays algorithm data-structures

假设我有三个数组:

require

并希望得到这样的输出:

array1 = [1,2,3,4];
array2 = [5,6,7];
array3 = [8,9,10,11];

因此垂直输出数组中的项目。

1,5,8,2,6,9,3,7,10,4,11

获得输出的最有效方法是什么?

2 个答案:

答案 0 :(得分:-1)

<?php
$array1 = [1,2,3,4];
$array2 = [5,6,7];
$array3 = [8,9,10,11];

    $a = count($array1);
    $b = count($array2);
    $c = count($array3); 
    $highest_number = max($a, $b, $c);
    $fvar = "";
    for ($x = 0; $x <= $highest_number; $x++) {
     if(!empty($array1[$x])){
         $fvar.=",".$array1[$x];
     }
          if(!empty($array2[$x])){
         $fvar.=",".$array2[$x];
     }

                  if(!empty($array3[$x])){
         $fvar.=",".$array3[$x];
     }
    } 
    $fvar  = ltrim($fvar,",");
    echo  $fvar ; 

?>

结果= 1,5,8,2,6,9,3,7,10,4,11 //更新以使其成为可以

的数组
$farray = explode(",",$fvar);

例子:
http://sandbox.onlinephpfunctions.com/code/5606877200b52828e94bbc43d31e9f335bf7a294

答案 1 :(得分:-2)

int i=0,n1= array1.length,n2=array2.length,n3=array3.length;

while(i<n1||i<n2||i<n3) {
  if(i<n1) print(array1[i]);
  if(i<n2) print(array2[i]);
  if(i<n3) print(array3[i]);
  i++;
}