-1

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);
?>
mickmackusa
  • 43,625
  • 12
  • 83
  • 136

4 Answers4

1

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

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.

heihei
  • 74
  • 6
0

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);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
-1

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);
MichaelvE
  • 2,558
  • 2
  • 9
  • 18