Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP insert array values to csv column

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there any simpler way to insert all the array values to the csv columns like above table?

>Solution :

Assuming that each sub-array contains the same count of values, you can achieve your goal with just a few lines of code:

  • use array_keys to get all the column names from your array
  • iterate each sub-array to compose the single row, assuming that each value of that row is in the same array index position
$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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading