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

rehman_invozone's avatar

remove duplicates array objects and merge a column

Hi, need help building a logic. it can be using core PHP methods or laravel collection methods. The problem is I have an array.

$contacts = [
   0: {ID: "1", tags: ["tag1"]}
   1: {ID: "2", tags: ["tag2"]}
   2: {ID: "3", tags: ["tag3"]}
   3: {ID: "1", tags: ["tag4"]}
   4: {ID: "4", tags: ["tag5"]}
]

What I want is if we have a duplicate id in the array as we have ID 1. remove them and merge the tag column.

$contacts = [
   0: {ID: "1", tags: ["tag1", "tag4"]}
   1: {ID: "2", tags: ["tag2"]}
   2: {ID: "3", tags: ["tag3"]}
   3: {ID: "4", tags: ["tag5"]}
]
0 likes
2 replies
vybeauregard's avatar

You could try looping through all the ID values with something like

collect($contacts)->where('ID', $id)->pluck('tags')->flatten();

and build up a new contacts array that way.

Tray2's avatar

You really should consider changing your database model, using json columns is a really bad practice.

Please or to participate in this conversation.