Reputation: 8350
In the example below, taken from Laravel documentation, if duplicate keys exist, the last matching element will be inserted into the plucked collection:
$collection = collect([
['brand' => 'Tesla', 'color' => 'red'],
['brand' => 'Pagani', 'color' => 'white'],
['brand' => 'Tesla', 'color' => 'black'],
['brand' => 'Pagani', 'color' => 'orange'],
['brand' => 'Renault', 'color' => null],
]);
$plucked = $collection->pluck('color', 'brand');
$plucked->all();
// ['Tesla' => 'black', 'Pagani' => 'orange', 'Renault' => null]
How can I get all duplicates into an array like below instead ?
[
'Tesla' => ['red', 'black'],
'Pagani' => ['white', 'orange'],
'Renault' => null,
]
Upvotes: 1
Views: 713
Reputation: 1938
I hope this will work as you want
$collection = collect([
['brand' => 'Tesla', 'color' => 'red'],
['brand' => 'Pagani', 'color' => 'white'],
['brand' => 'Tesla', 'color' => 'black'],
['brand' => 'Pagani', 'color' => 'orange'],
['brand' => 'Renault', 'color' => null],
]);
$plucked = $collection->groupBy('brand')->map(function ($brands) {
$data = $brands->pluck('color');
return $data[0] ? $data : null;
});
Upvotes: 4
Reputation: 12188
there is a method specialized for this case, it's mapToGroups:
The mapToGroups method groups the collection's items by the given closure. The closure should return an associative array containing a single key / value pair, thus forming a new collection of grouped values:
$collection = collect([
['brand' => 'Tesla', 'color' => 'red'],
['brand' => 'Pagani', 'color' => 'white'],
['brand' => 'Tesla', 'color' => 'black'],
['brand' => 'Pagani', 'color' => 'orange'],
['brand' => 'Renault', 'color' => null],
]);
$grouped = $collection->mapToGroups(function ($item, $key) {
return [$item['brand'] => $item['color']];
});
Upvotes: 4