3

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:

  • the keys are always in the same order
  • a list of all possible keys can be generated if necessary

Are there any tricks with PHP array functions that I can apply?

Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111

1 Answers1

4

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);
Gino Pane
  • 4,740
  • 5
  • 31
  • 46