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 Answer 1

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) ;
Sign up to request clarification or add additional context in comments.

6 Comments

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?
@kpurdon Upgraded the code for better performance, as you dont have to call function in loop.
@kpurdon In fact, I find it very efficient, because using array_* functions is generally slower, than looping arrays and performing simple actions.
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.
Yeah, you are right about 2d array, it doesnt work this way. I just misunderstood the function. But anyways, thanks for the task.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.