I have a large (size ~ 12k) 2D array of data like below and I want to insert these data into a csv file.
$data = array
(
'a' => array
(
0 => 111,
1 => 222,
2 => 333,
3 => 444,
),
'b' => array
(
0 => 555,
1 => 666,
2 => 777,
3 => 888,
),
'c' => array
(
0 => 999,
1 => 000,
2 => 111,
3 => 222,
),
);
Here 'a', 'b', and 'c' would be the CSV header row, and corresponding array values should be inserted like below:-
a | b | c |
---|---|---|
111 | 555 | 999 |
222 | 666 | 000 |
333 | 777 | 111 |
444 | 888 | 222 |
I know fputcsv
can be used to insert the data but it insert the array values as a row in the csv but in my case I want to insert the array values to a csv column.
Is there any simpler way to insert all the array values to the csv columns like above table?
Assuming that each sub-array contains the same count of values, you can achieve your goal with just a few lines of code:
$data = array
(
'a' => array
(
0 => 111,
1 => 222,
2 => 333,
3 => 444,
),
'b' => array
(
0 => 555,
1 => 666,
2 => 777,
3 => 888,
),
'c' => array
(
0 => 999,
1 => 000,
2 => 111,
3 => 222,
),
);
$fp = fopen('file.csv', 'w');
// headers
fputcsv($fp, array_keys($data));
// rows contents
for($i = 0; $i<count(current($data)); $i++) {
$row = [];
foreach($data as $k => $v) {
$row[] = $v[$i];
}
fputcsv($fp, $row);
}
fclose($fp);
Try it online on https://onlinephp.io/c/735bc, with this results:
a,b,c
111,555,999
222,666,0
333,777,111
444,888,222
In the official documentation you can find many other useful array functions.