collection中reduce创建lookup数组

有如下数组

$employees = [
    [
        'name' => 'example',
        'email' => '[email protected]',
        'company' => 'example Inc.'
    ],
    [
        'name' => 'Lucy',
        'email' => '[email protected]',
        'company' => 'ibm Inc.'
    ],
    [
        'name' => 'Taylor',
        'email' => '[email protected]',
        'company'=>'Laravel Inc.'
    ]
];

通过计算将其转化成如下格式

$lookup = [
    'example' => '[email protected]',
    'Lucy' => ‘[email protected]’,
    'Taylor'=> '[email protected]'
];

使用foreach解决

$emails = [];
foreach ($employees as $key => $value) {
    $emails[$value['name']] = $value['email'];
}
dd($emails);

使用collection的reduce方法

$emails = collect($employees)->reduce(function($emailLookup, $employee){
    $emailLookup[$employee['name']] = $employee['email'];
    return $emailLookup;
},[]);

dd($emails);

使用 pluck 方法

$emails = collect($employees)->pluck('name', 'email');
dd($emails);
Copyright © http://blog.webfsd.com 2018 all right reserved,powered by Gitbook该文件修订时间: 2019-05-21 04:55:26

results matching ""

    No results matching ""