如何将数组值拆分为3列?

时间:2017-08-16 09:58:51

标签: php arrays

$data =( [01] => 0 [02] => 0 [03] => 1 [04] => 0 [05] => 0 [06] => 0 
         [07] => 0 [08] => 0 [09] => 1 [10] => 0 [11] => 0 [12] => 0 
         [13] => 0 [14] => 0 [15] => 0 [16] => 0 [17] => 0 [18] => 0 
         [19] => 0 [20] => 0 [21] => 0 [22] => 0 [23] => 0 [24] => 0 
         [25] => 0 [26] => 0 [27] => 0 [28] => 0 [29] => 0 [30] => 0 
         [31] => 0)

期待输出:

0=>([01]=>0 [11]=>0 [21]=>0)
1=>([02]=>0 [12]=>0 [22]=>0)
2=>([03]=>0 [13]=>0 [23]=>0)
upto 
10=>([10]=>0 [20]=>0 [30]=>0)

这是我当前的代码尝试

foreach ($data as $k => $v) { 
   for ($i=0; $i<10;$i++){
      if ($k <= 10) { $one[$k] = $v; } 
      elseif($k>10 && $k<=20) { $two[$k]=[$v]; } 
      else { $three[$k] = $v; } 
   }
} 

我使用了关联数组概念(有键和值),我已经从单个数组拆分成3个数组但是得到的结果如(1到10),(11-20)和(21-30),相反,我想要(1-11-21)(2-12-22)。

3 个答案:

答案 0 :(得分:0)

这应该有效:

 <?php
 $data =array("01" => "0", "02" => "0", "03" => "1", "04" => "0", "05" => "0", "06" => "0", "07" => "0", "08" => "0", "09" => "1", "10" => "0", "11" => "0", "12" => "0", "13" => "0", "14" => "0", "15" => "0", "16" => "0", "17" => "0", "18" => "0", "19" => "0", "20" => "0", "21" => "0", "22" => "0", "23" => "0", "24" => "0 ", "25" => "0", "26" => "0", "27" => "0", "28" => "0", "29" => "0", "30" => "0 " );

 $output = array();

 print_r($data);
 foreach($data as $key =>$value)
 {
     $index = $key % 10;
     $output[$index][] = $value;
 }
 print_r($output);
 ?>

答案 1 :(得分:0)

希望这项工作。

 $data = array(10, 20, 31, 40, 50, 60,70, 80, 91, 100, 110, 120,130, 140, 150, 160, 170, 180,190 ,200 ,210 ,220, 230, 240,25, 260, 270, 280, 290, 300, 
     310);
$finalarr = array();
foreach ($data as $k => $v) { 
   for($i = $k;$i<count($data);$i+=10){
      $finalarr[$k][] = $data[$i];
   }
} 

print_r($finalarr);

答案 2 :(得分:0)

#Thanks Dude ...... 我通过以下代码获得了预期的结果:

  foreach($data as $ke=>$va){
                    for($i=1; $i<=10; $i++){
                            for($j=$i; $j<=31; $j+=10){
                                    if($j==$ke){
                                            if($j==31){
                                                    $op[11][$j]=$va;
                                                    $op[11][' ']=' ';
                                                    $op[11]['  ']=' ';
                                            }
                                            else if($j!==31){
                                                    $op[$i][$j]=$va;
                                            }
                                    }
                            }
                    }
            }