2

There are three single dimensional arrays that needs to be saved in csv

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

I need to save the above arrays in the csv like the following example-

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

I have tried the following code but its not saving in that format

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

Output

1,2,3
a,b,c
x,y,z
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
blakcaps
  • 2,647
  • 10
  • 46
  • 71

5 Answers5

2
foreach ($arr1 as $key => $value) {
    fputcsv($handle, array($value, $arr2[$key], $arr3[$key]));
}
deceze
  • 510,633
  • 85
  • 743
  • 889
2

Transpose the data before writing to the 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);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
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);
?>

Expected output:


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

ReeCube
  • 2,545
  • 17
  • 23
  • You need to strip the trailing delimiter from each row before adding the \n. CSV rows are terminated by a newline, not a delimiter+newline. – The Blue Dog Feb 27 '14 at 08:43
0

try like below:-

$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);

output

1   a   x
2   b   y
3   c   z
Rakesh Sharma
  • 13,680
  • 5
  • 37
  • 44
0

Try this,Just take the transpose of the array before 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);
 ?>

Output

 1,a,x
 2,b,y
 3,c,z
Shijin TR
  • 7,516
  • 10
  • 55
  • 122