How to save a single column from a multidimensional array as a .csv file?

516 Views Asked by At

The following code exports the whole array into the .csv file, but I only want to export a specific column.

<?php 
$test = array(array("eric", 7),array("nancy" ,8),array("dave", 10));
$fp = fopen('new.csv', 'w');
foreach ($test as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>
4

There are 4 best solutions below

0
On

You can do this by removing the fields you want to exclude from the $fields array before calling fputcsv(). Remove the fields using the unset() function passing the element's key.

Example

Assuming you want to have only a list of the name, you'd do the following

$test = array(array("eric", 7),array("nancy" ,8),array("dave", 10));
$fp = fopen('new.csv', 'w');
foreach($test as $row){
    unset($row[1]);
    // Removing the index 1 leaves the array with just one field which will be written to the new.csv file.
    fputcsv($fp,$row);
}
fclose($fp)
0
On

If you just want to export just the names, for example, do the following:

$test = array(array("eric", 7),array("nancy" ,8),array("dave", 10));
$fp = fopen('new.csv', 'w');
foreach ($test as $fields) {
fputcsv($fp, $fields[0]);
}
fclose($fp);
0
On

do with the array before you put it into the csv. for example , if you don't want the first colum ,remove it. you can use the function array_shift.
this can not affect the original array. like these code.

<?php 
$test = array(array("eric", 7),array("nancy" ,8),array("dave", 10));
$fp = fopen('new.csv', 'w');
foreach ($test as $fields) {
    array_shift($fields);
    fputcsv($fp, $fields);
}

fclose($fp);
?>

just keep columns you want to the csv.

0
On

In your loop, there is no need to modify the copy of the array row (with unset(), array_shift(), etc.), simply deliver the column value that you wish to use as a single-element array.

The second parameter of fputcsv() MUST be an array. This is why the $row[0] value is wrapped in square brackets.

If you want to save the name values to your file, use $row[0].

If you want to save the numeric values to your file, use $row[1].

Code:

$test = ["eric", 7], ["nancy", 8], ["dave", 10]];
$fp = fopen("new.csv", 'w');
foreach ($test as $row) {
    fputcsv($fp, [$row[0]]);  // if you want first column values
}
fclose($fp);