Given an array of the form
[
['id' => 1, 'name' => 'foo', 'description' => 'the foo described'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'description' => 'the one that shall not be named'],
]
i.e. each element is an associative array where most values are optional.
What's the best way to export it to a CSV file?
"id","name","description"
"1","foo","the foo described"
"2","bar",""
"3","","the one that shall not be named"
To do so, I probably need to convert the array to this:
[
['id' => 1, 'name' => 'foo', 'description' => 'the foo described'],
['id' => 2, 'name' => 'bar', 'description' => ''],
['id' => 3, 'name' => '', 'description' => 'the one that shall not be named'],
]
If it helps:
Are there any tricks with PHP array functions that I can apply?
You can use array_fill_keys, array_map and array_merge for your issue:
<?php
$keys = ['id', 'name', 'description'];
$template = array_fill_keys($keys, '');
$array = [
['id' => '1', 'name' => 'foo', 'description' => 'description 1'],
['id' => '2', 'name' => 'bar'],
['id' => '3', 'description' => 'description 2']
];
$normalized = array_map(function($item) use ($template) {
return array_merge($template, $item);
}, $array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With