Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

deepu07's avatar
Level 11

Laravel Map key and values include duplicate records

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.

0 likes
5 replies
deepu07's avatar
Level 11

@michaloravec thanks for the reply. I have id is a unique key but I wanna map key and value as name and department only, not id.

Is there any way to use pluck in this case? I tried with pluck but still, it is giving distinct values.

MichalOravec's avatar

How I said, what you want is not possible, because Sales as a key will be replaced in the array.

This will be a result.

[
     "Sales" => "John",
     "Marketing" => "Jane"
]
1 like
MichalOravec's avatar

No, because same key in the collection wil be replaced as well.

Please or to participate in this conversation.