0

Simple Example:

$a = array(1,2,3,4);
$b = array(10,20,30,40);
$c = array(100,200,300,400);

If I execute the following:

$fp = fopen('somefile.csv','w');
fputcsv($fp,$a);
fputcsv($fp,$b);
fputcsv($fp,$c);
fclose($fp);

I get a file that looks like this:

1,2,3,4
10,20,30,40
100,200,300,400

As I would expect. However what I want is:

1,10,100
2,20,200
3,30,300
4,40,400

Is this possible without just looping and writing each index from each array?

1 Answers1

4

What's wrong with using loops? It is so easy.

$fp = fopen('somefile.csv','w');
for ($i = 0 ; $i < 4 ; $i++){
  fputcsv($fp, array($a[$i], $b[$i], $c[$i])) ;
}
fclose($fp) ;
David G
  • 6,803
  • 4
  • 28
  • 51
sybear
  • 7,837
  • 1
  • 22
  • 38
  • I wonder how efficient it would be if say, there were 5 arrays with 100,000 elements? Guess i'll have to test and find out. Any thoughts? –  Feb 19 '13 at 20:21
  • @kpurdon Upgraded the code for better performance, as you dont have to call function in loop. – sybear Feb 19 '13 at 20:24
  • @kpurdon In fact, I find it very efficient, because using `array_*` functions is generally slower, than looping arrays and performing simple actions. – sybear Feb 19 '13 at 20:36
  • I'm not sure the "performance" one works. For me it just writes "Array,Array..." as strings to the CSV file. Adding a foreach() and looping through each sub-array and writing, solves. So is it faster to compile a large array then write in a foreach loop. Or just write from the first loop. –  Feb 19 '13 at 21:17
  • Yeah, you are right about 2d array, it doesnt work this way. I just misunderstood the function. But anyways, thanks for the task. – sybear Feb 19 '13 at 21:32
  • fputcsv instead of fputscv =/ – Steve Yancharas Jr. Jun 15 '14 at 02:13