The Manh Nguyen
The Manh Nguyen

Reputation: 465

mapWithKeys in laravel ,i dont understand how do it work?

I saw the example of laravel, but i dont understand how do it work.

for this example:

$collection = collect([
    [
        'name' => 'John',
        'department' => 'Sales',
        'email' => '[email protected]'
    ],
    [
        'name' => 'Jane',
        'department' => 'Marketing',
        'email' => '[email protected]'
    ]
]);

$keyed = $collection->mapWithKeys(function ($item) {
    return [$item['email'] => $item['name']];
});

$keyed->all();

someone can explain detail of it?

Upvotes: 0

Views: 1353

Answers (1)

Shailendra Gupta
Shailendra Gupta

Reputation: 1128

$collection = collect([
    [
        'name' => 'John',
        'department' => 'Sales',
        'email' => '[email protected]'
    ],
    [
        'name' => 'Jane',
        'department' => 'Marketing',
        'email' => '[email protected]'
    ]
]);

$keyed = $collection->mapWithKeys(function ($item) {
   //this line takes one array of collection object in item array and  make a key of its email and store name on that email key  
    return [$item['email'] => $item['name']];
});

$keyed->all();

Upvotes: 1

Related Questions