How can one efficiently filter and format data for fputcsv output in PHP?
To efficiently filter and format data for fputcsv output in PHP, you can use array_filter to remove any unwanted data and array_map to format the data before writing it to a CSV file with fputcsv.
// Sample data array
$data = [
['John', 'Doe', 'john.doe@example.com'],
['Jane', 'Smith', 'jane.smith@example.com'],
['Alice', 'Johnson', 'alice.johnson@example.com'],
];
// Filter and format data before writing to CSV
$filteredData = array_map(function ($row) {
return [
$row[0], // First name
$row[2], // Email
];
}, array_filter($data, function ($row) {
// Filter out rows where last name is 'Smith'
return $row[1] != 'Smith';
}));
// Open file handle for writing
$fp = fopen('output.csv', 'w');
// Write data to CSV file
foreach ($filteredData as $row) {
fputcsv($fp, $row);
}
// Close file handle
fclose($fp);