How to Flatten data along with key in Lumen/Laravel

134 Views Asked by At

I followed this tutorial. It was worked. How to get json to flatten along with key in lumen/laravel. I need key and value.

Code I used:

public function index(){
$collection = collect([
        'name' => 'Hardik', 
        'role' => ['admin', 'manager', 'superadmin'],
        'multi' => 
            [
                'one',
                'two' => ['two1', 'two3'],
                'three'
            ],
    ]);

$flattened = $collection->flatten();
      
dd($flattened);
}

Actual Output:

Illuminate\Support\Collection Object(

[items:protected] => Array

    (

        [0] => Hardik

        [1] => admin

        [2] => manager

        [3] => superadmin

        [4] => one

        [5] => two1

        [6] => two3

        [7] => three

    ))

Here the keys coming as integer from 0. But I need it as the key from the array.

Output expected:

  ['name'] => Hardik

    ['role'] => admin

    ['role'] => manager

    ['role'] => superadmin

    ['multi.one'] => one

    ['multi.two'] => two1

    ['multi.two'] => two3

    ['multi.three'] => three

How to get it?

0

There are 0 best solutions below