合并Laravel个采集结果,聚合一个字段
Combine Laravel collection results, aggregate one field
我有一个包含重复结果的集合,但在相关字段中有不同的数据。我想消除重复项,但通过组合该字段的值来保留其他数据。我似乎找不到一个好的方法来做到这一点。我的结果集如下所示:
"bankers" => Collection {#663 ▼
#items: array:5 [▼
0 => Collection {#465 ▼
#items: array:5 [▼
"banker_id" => 13
"banker_name" => "John Banker"
"type" => "lending"
"deal_score" => 1
]
}
1 => Collection {#455 ▼
#items: array:5 [▼
"banker_id" => 62667
"banker_name" => "Harvey Aandreau"
"type" => "lending"
"deal_score" => 0
]
}
2 => Collection {#419 ▼
#items: array:6 [▼
"banker_id" => 13
"banker_name" => "John Banker"
"type" => "quotes"
"deal_score" => 1
]
}
3 => Collection {#410 ▼
#items: array:6 [▼
"banker_id" => 297
"banker_name" => "Melissa Jablonsky"
"type" => "quotes"
"deal_score" => 1
]
}
]
}
我想删除第二个重复项 "John Banker",但将 "type" 字段的值添加到上一条记录,如:
"bankers" => Collection {#663 ▼
#items: array:5 [▼
0 => Collection {#465 ▼
#items: array:5 [▼
"banker_id" => 13
"banker_name" => "John Banker"
"type" => "lending, quotes"
"deal_score" => 1
]
}
1 => Collection {#455 ▼
#items: array:5 [▼
"banker_id" => 62667
"banker_name" => "Harvey Aandreau"
"type" => "lending"
"deal_score" => 0
]
}
3 => Collection {#410 ▼
#items: array:6 [▼
"banker_id" => 297
"banker_name" => "Melissa Jablonsky"
"type" => "quotes"
"deal_score" => 1
]
}
]
}
我需要保留当前订单。 "type" 字段可以根据需要更改为数组。如有任何建议,我们将不胜感激。
感谢 Joseph Silber 提出以下建议:
$bankers->groupBy('banker_name')->map(function ($bankers) {
return array_merge($banker[0]->all(), [
'type' => $bankers->pluck('type')->implode(',');
]);
});
我有一个包含重复结果的集合,但在相关字段中有不同的数据。我想消除重复项,但通过组合该字段的值来保留其他数据。我似乎找不到一个好的方法来做到这一点。我的结果集如下所示:
"bankers" => Collection {#663 ▼
#items: array:5 [▼
0 => Collection {#465 ▼
#items: array:5 [▼
"banker_id" => 13
"banker_name" => "John Banker"
"type" => "lending"
"deal_score" => 1
]
}
1 => Collection {#455 ▼
#items: array:5 [▼
"banker_id" => 62667
"banker_name" => "Harvey Aandreau"
"type" => "lending"
"deal_score" => 0
]
}
2 => Collection {#419 ▼
#items: array:6 [▼
"banker_id" => 13
"banker_name" => "John Banker"
"type" => "quotes"
"deal_score" => 1
]
}
3 => Collection {#410 ▼
#items: array:6 [▼
"banker_id" => 297
"banker_name" => "Melissa Jablonsky"
"type" => "quotes"
"deal_score" => 1
]
}
]
}
我想删除第二个重复项 "John Banker",但将 "type" 字段的值添加到上一条记录,如:
"bankers" => Collection {#663 ▼
#items: array:5 [▼
0 => Collection {#465 ▼
#items: array:5 [▼
"banker_id" => 13
"banker_name" => "John Banker"
"type" => "lending, quotes"
"deal_score" => 1
]
}
1 => Collection {#455 ▼
#items: array:5 [▼
"banker_id" => 62667
"banker_name" => "Harvey Aandreau"
"type" => "lending"
"deal_score" => 0
]
}
3 => Collection {#410 ▼
#items: array:6 [▼
"banker_id" => 297
"banker_name" => "Melissa Jablonsky"
"type" => "quotes"
"deal_score" => 1
]
}
]
}
我需要保留当前订单。 "type" 字段可以根据需要更改为数组。如有任何建议,我们将不胜感激。
感谢 Joseph Silber 提出以下建议:
$bankers->groupBy('banker_name')->map(function ($bankers) {
return array_merge($banker[0]->all(), [
'type' => $bankers->pluck('type')->implode(',');
]);
});