hondnl
4 months ago

Map array values to collection of items

Posted 4 months ago by hondnl

How would one do the following elegantly with laravel collections ?

Map the values of the $baseMap as keys to the collection.

The baseMap :

    $baseMap = [
                'name' => 'new_name',
                'year' => 'new_year',
            ];

The collection :

     $items = collect([
                [
                    'name' => 'name1',
                    'year' => '1000',
                    'not_in_basemap' => 'foo'
                ],
                [
                    'name' => 'name2',
                    'year' => '2000',
                    'not_in_basemap' => 'foo'
                ],
                //...
            ]);

The end result :

    $result =[
                [
                    'new_name' => 'name1',
                    'new_year' => '1000',
                 
                ],
                [
                    'new_name'=> 'name2',
                    'new_year' => '2000',
                 
                ],
            ];

I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!

Please sign in or create an account to participate in this conversation.