laravellaravel-5laravel-5.4laravel-collection

Laravel collections: Flatten with full key name


Is there a way with Laravel Collections to flatten an array with key "namespace". Something like:

$a = collect([
    'id' => 1,
    'data' => [
        'a' => 2,
        'b' => 3
    ]
]);

$a = $a->flattenWithKeysNamespace(); // <-- this does not exists

// Should returns: 
// ['a' => 1, 'data.b' => 2, 'data.c' => 3]; // <-- I would like this.

I know I can do this in raw PHP, or with some assembly of Collection functions, but sometimes I miss something in Laravel Collection documentation. So is there a simple way with Collection functions to do this?


Solution

  • I think you are right is that there is no "Laravel way" to do this. Answers like this show a way to do so in PHP if you are willing to convert your Collection to an array, but since you mention raw PHP I assume you already found this kind of solution.

    I think your best bet in doing it using Collection methods is by writing a similar function to the one I linked, but use functions like flatMap() and recursively call your function when your element is also a collection.