Search code examples
phparrayslaravelgroupinglaravel-collection

Laravel array group by and merge each group


I have such an array, how can I group by date and merge each group?

$input =  [
    [
        'date' => '2018-09-25',
        'foo' => 'value1',
    ],
    [
        'date' => '2018-09-25',
        'bar' => 'value2'
    ],
    [
        'date' => '2018-09-26',
        'baz' => 'value3'
    ]
];

That in the end it turned out like this:

[
    [
        'date' => '2018-09-25'
        'foo' => 'value1'
        'bar' => 'value2'
    ],
    [
        'date' => '2018-09-26'
        'baz' => 'value3'
    ]
]

Solution

  • You can use laravel collection.

    First you need to group by groupBy method, then map each group and merge every child array.

    Code:

    $result = collect($input)
        ->groupBy('date')
        ->map(function ($item) {
            return array_merge(...$item->toArray());
        });
    

    You will get this collection:

    enter image description here

    And in the end remove the keys(date), you can use values, and simply convert the collection to an array(toArray).

    End Code:

    $result = collect($input)
        ->groupBy('date')
        ->map(function ($item) {
            return array_merge(...$item->toArray());
        })
        ->values()
        ->toArray();