How can array_walk_recursive() be used to manipulate CSV output in PHP?
To manipulate CSV output in PHP using array_walk_recursive(), you can iterate through a multidimensional array representing the CSV data and apply a callback function to manipulate each value before outputting it. This allows you to modify the data as needed before writing it to a CSV file or displaying it to the user.
$data = [
['John', 'Doe', 'john.doe@example.com'],
['Jane', 'Smith', 'jane.smith@example.com'],
];
// Define a callback function to manipulate each value
function manipulateValue(&$value, $key)
{
$value = strtoupper($value); // Convert value to uppercase
}
// Apply the callback function to each value in the multidimensional array
array_walk_recursive($data, 'manipulateValue');
// Output the data as CSV
$fp = fopen('output.csv', 'w');
foreach ($data as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Related Questions
- In what scenarios would it be advisable to consider using frames or iframes to maintain a consistent URL in PHP?
- Is using htaccess sufficient to protect directories from external access in PHP?
- What are the potential pitfalls of using nested foreach loops to iterate through multi-dimensional arrays in PHP?