Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalize list of associative arrays to write to CSV [duplicate]

Tags:

arrays

php

csv

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?

like image 701
Fabian Schmengler Avatar asked Feb 01 '26 23:02

Fabian Schmengler


1 Answers

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);
like image 156
Gino Pane Avatar answered Feb 04 '26 13:02

Gino Pane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!