多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] # 问题描述 我们想把数组 ~~~ $employees=[ [ 'name'=>'JellyBool', 'email'=>'jellybool@outlook.com', 'company'=>'Laravist Inc' ], [ 'name'=>'Taylor', 'email'=>'Taylor@laravel.com', 'company'=>'Laravel Inc' ] ]; ~~~ 变成下面这个样子,name的值作为key,email的值为value ~~~ $lookup=[ 'JellyBool'=>'jellybool@outlook.com', 'Taylor'=>'Taylor@laravel.com', ]; ~~~ # 解决 ~~~ $emails=collect($employees)->map(function($employee){ $emailLookup=[]; $emailLookup[$employee['name']]=$employee['email']; return $emailLookup; }); dd($emails); ~~~ 这种是形成结构了,但是多了层数组 ~~~ Collection {#166 #items: array:2 [ 0 => array:1 [ "JellyBool" => "jellybool@outlook.com" ] 1 => array:1 [ "Taylor" => "Taylor@laravel.com" ] ] } ~~~ 如果我们使用flatten ~~~ $emails=collect($employees)->map(function($employee){ $emailLookup=[]; $emailLookup[$employee['name']]=$employee['email']; return $emailLookup; })->flatten(1); ~~~ key值就变了,是0,1不是我们的name ~~~ Collection {#159 #items: array:2 [ 0 => "jellybool@outlook.com" 1 => "Taylor@laravel.com" ] } ~~~ ## reduce 将集合缩减到单个数值,该方法会将每次迭代的结果传入到下一次迭代 第一次迭代时 $carry 的数值为 null;然而你也可以传入第二个参数进 reduce 以指定它的初始值: ~~~ $emails=collect($employees)->reduce(function($emailLookup,$employee){ $emailLookup[$employee['name']]=$employee['email']; return $emailLookup; },[]); dd($emails); ~~~