Laravel中的mapWithKeys,我不知道它如何工作?

时间:2018-10-29 10:11:22

标签: laravel laravel-5 laravel-collection

我看到了laravel的例子,但是我不明白它是如何工作的。

this example

$collection = collect([
    [
        'name' => 'John',
        'department' => 'Sales',
        'email' => 'john@example.com'
    ],
    [
        'name' => 'Jane',
        'department' => 'Marketing',
        'email' => 'jane@example.com'
    ]
]);

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

$keyed->all();

有人可以解释它的细节吗?

1 个答案:

答案 0 :(得分:1)

$collection = collect([
    [
        'name' => 'John',
        'department' => 'Sales',
        'email' => 'john@example.com'
    ],
    [
        'name' => 'Jane',
        'department' => 'Marketing',
        'email' => 'jane@example.com'
    ]
]);

$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();