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?
3
Answers
Assuming that each sub-array contains the same count of values, you can achieve your goal with just a few lines of code:
Try it online on https://onlinephp.io/c/735bc, with this results:
In the official documentation you can find many other useful array functions.
Since CSV files are fundamentally written row by row, you’ll need to:
Assuming all your sub-arrays have the same number of keys, you could set up this way:
And then your loop would look like this:
Demo echoing the data rather than writing with
fputcsv
: https://3v4l.org/P5rtUAlternatively, you could loop using a list of row keys, rather than assuming they’re sequentially numbered. For instance, taking the keys from the first sub-array:
Then use
foreach
instead offor
:There exists an array_column function that might be of help:
output: