PHP将数组写入Csv

时间:2014-02-27 08:32:44

标签: php arrays csv

有三个单维数组需要保存在csv

$arr1=array(1,2,3);
$arr2=array('a','b','c');
$arr3=array('x','y','z');

我需要在csv中保存上面的数组,如下例所示 -

1,a,x
2,b,y
3,c,z 

我尝试过以下代码,但不以该格式保存

$handle = fopen('file.csv', 'w');
$data=array($arr1,$arr2,$arr3);
foreach ($data as $line) {
    fputcsv($handle, $line);
}
fclose($handle);

输出

1,2,3
a,b,c
x,y,z

5 个答案:

答案 0 :(得分:2)

foreach ($arr1 as $key => $value) {
    fputcsv($handle, array($value, $arr2[$key], $arr3[$key]));
}

答案 1 :(得分:2)

在写入CSV之前转置数据

$data = array($arr1,$arr2,$arr3);
$transposedData = call_user_func_array(
    'array_map',
    array_merge(
        array(NULL),
        $data
    )
);

$handle = fopen('file.csv', 'w');

foreach ($transposedData  as $line) {
    fputcsv($handle, $line);
}
fclose($handle);

答案 2 :(得分:0)

<?php
   $arr1=array(1,2,3);
   $arr2=array('a','b','c');
   $arr3=array('x','y','z');

   $output = '';

   $data=array($arr1,$arr2,$arr3);
   $size=count($data[0]);
   //all arrays must have the same size! and $data must contain at least one item

   for ($i = 0; $i < $size; $i++) {
      foreach ($data as $arr) {
         $output .= $arr[$i] . ';';
      }
      $output .= "\n";
   }

   file_put_contents($output);
?>

预期产出:


    1;a;x;
    2;b;y;
    3;c;z;

答案 3 :(得分:0)

尝试如下: -

$arr1=array(1,2,3);
$arr2=array('a','b','c');
$arr3=array('x','y','z');
$handle = fopen('file.csv', 'w');
for($i=0; $i<count($arr1); $i++) {
  $data=array($arr1[$i],$arr2[$i],$arr3[$i]);
  fputcsv($handle, $data);
}
fclose($handle);

输出

1   a   x
2   b   y
3   c   z

答案 4 :(得分:0)

试试这个,只需在 fputcsv

之前进行数组的转置
  <?php
 $arr1=array(1,2,3);
 $arr2=array('a','b','c');
 $arr3=array('x','y','z');
 $data=array($arr1,$arr2,$arr3);
 $rows = count($data);
 $cols = count($data[0]);
 $ridx = 0;
 $cidx = 0;

 $out = array();

 foreach($data as $rowidx => $row){
 foreach($row as $colidx => $val){
    $out[$ridx][$cidx] = $val;
    $ridx++;
    if($ridx >= $rows){
        $cidx++;
        $ridx = 0;
    }
}
}


$handle = fopen('file.csv', 'w');

 foreach ($out as $line) {
   fputcsv($handle, $line);
}
fclose($handle);
 ?>

<强>输出

 1,a,x
 2,b,y
 3,c,z