How can str_getcsv and Array Operations be utilized to manipulate CSV data in PHP for specific file generation?
To manipulate CSV data in PHP for specific file generation, you can use the str_getcsv function to parse the CSV data into an array, and then perform various array operations to manipulate the data as needed. This can include filtering, sorting, transforming, or combining the data before generating a new CSV file.
// Read CSV data from a file
$csvData = file_get_contents('data.csv');
// Parse CSV data into an array
$rows = array_map('str_getcsv', explode("\n", $csvData));
// Perform array operations to manipulate the data
// For example, filter out rows based on a condition
$filteredRows = array_filter($rows, function($row) {
return $row[1] == 'specific_value';
});
// Generate new CSV data from the manipulated array
$newCsvData = implode("\n", array_map(function($row) {
return implode(',', $row);
}, $filteredRows));
// Write the new CSV data to a file
file_put_contents('new_data.csv', $newCsvData);