Laravel中按客户邮箱分组集合的实现问题
问题
我有一个名为$customerRecords的数组,希望按客户的邮箱对该数组中的数据进行分组。
原数组结构
$customerRecords = [ [ "id" => 1, "note" => "This is note 1", "customer" => [ [ "id" => 1, "user_id" => 34, "email" => "doe@mailnator.com", "phone" => "9829484857" ] ] ], [ "id" => 2, "note" => "This is note 2", "customer" => [ [ "id" => 2, "user_id" => 34, "email" => "john@mailnator.com", "phone" => "9829484857" ] ] ], [ "id" => 3, "note" => "This is a note 3", "customer" => [ [ "id" => 2, "user_id" => 34, "email" => "john@mailnator.com", "phone" => "9829484857" ] ] ], ];
期望分组结果
[ "doe@mailnator.com" => [ [ "id" => 1, "note" => "This is note 1", "customer" => [ [ "id" => 1, "user_id" => 34, "email" => "doe@mailnator.com", "phone" => "9829484857" ] ] ] ], "john@mailnator.com" => [ [ "id" => 2, "note" => "This is note 2", "customer" => [ [ "id" => 2, "user_id" => 34, "email" => "john@mailnator.com", "phone" => "9829484857" ] ] ], [ "id" => 3, "note" => "This is a note 3", "customer" => [ [ "id" => 2, "user_id" => 34, "email" => "john@mailnator.com", "phone" => "9829484857" ] ] ] ] ]
尝试过的代码(未成功)
return collect($customerRecords)->groupBy('customer.email');
解决方法
问题出在customer是一个数组(而非单个对象/关联数组),直接使用customer.email无法正确定位到邮箱值。你需要通过闭包自定义分组逻辑:
return collect($customerRecords)->groupBy(function ($item) { // 取customer数组首个元素的email作为分组键 return $item['customer'][0]['email']; });
说明
- 原代码的
groupBy('customer.email')适用于customer为单个对象的场景,但你的数据中每个记录的customer是包含一个元素的数组,因此必须先访问数组的第一个元素$item['customer'][0],再获取email字段。 - 如果业务场景中
customer数组可能包含多个元素,你需要根据需求调整逻辑(例如合并多邮箱分组、取特定位置元素等),但从示例数据来看,上述代码可满足需求。
内容的提问来源于stack exchange,提问作者Bold
相关产品推荐
相关产品推荐

