Question

m having 3 arrays say:

$first_array = array('val11','val21','val31');
$Second_array = array('val12','val22','val32');
$third_array = array('val13','val23','val33');

Is it possible to store this array values using fgetcsv() function of php in to each column, i mean,
first_array should be store in first column,
second array in second columnn and third to third.. so the data should be like

val11 val12 val31
val21 val22 val32
val31 val32 val33

is there anyway please let me know . thanks

Was it helpful?

Solution

The easiest way is to flip the arrays from columns to rows.

Assuming that all the arrays have the same number of elements, this should do the job:

$rows = array();

// Converts the arrays of columns into arrays of rows
$length = count($first_array);
for ($i = 0; $i < $length; $i++) {
  $rows[$i] = array($first_array[$i], $second_array[$i], $third_array[$i]);
}

// Writes the rows to the file
$fp = fopen('outfile.csv', 'w');
foreach ($rows as $row) {
  fputcsv($fp, $row);
}
fclose($fp);

OTHER TIPS

Check this code

<?php
    $list = array (
        array('aaa', 'bbb', 'ccc', 'dddd'),
        array('123', '456', '789'),
        array('"aaa"', '"bbb"')
    );
    $fp = fopen('test.csv', 'w');
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
    }
    fclose($fp);
 ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top