You have to have a unique key in the array. So your desire output is not possible.
Use mapToGroups()
Docs: https://laravel.com/docs/8.x/collections#method-maptogroups
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi Mates, here is my input
$students = [
[
'id' => 1,
'name' => 'John',
'department' => 'Sales',
],
[
'id' => 2,
'name' => 'Jane',
'department' => 'Marketing',
],
[
'id' => 3,
'name' => 'John',
'department' => 'Sales'
],
];
so my desire output is
$studentLookup = [
'Sales' => 'John',
'Marketing' => 'Jane',
'Sales' => 'Dave',
];
I tried this logic didn't work for me
$studentLookup = $students->reduce(function ($studentLookup, $student) {
$studentLookup[$student['department']] = $student['name'];
return $studentLookup;
}, []);
any help would be great. Thanks in advance.
Please or to participate in this conversation.