I have an array containing several objects.
$products = [
{"id":"1","random":"sadasd","mergethis":"Ding"},
{"id":"2","random":"assdfsadf","mergethis":"Ding"},
{"id":"2","random":"assdfsadf","mergethis":"Flop"},
{"id":"2","random":"assdfsadf","mergethis":"Bips"},
{"id":"3","random":"sdfss","mergethis":"Flung"},
{"id":"3","random":"sdfss","mergethis":"Rorg"},
{"id":"4","random":"asdasdddaf","mergethis":"Shwung"}
]
I'm trying to iterate trough this array and when the id
is allready present in the array, I want to add the value of mergethis
with the first hit that has the same id
, seperated with a comma, and then unset the object from the array.
So my expected outcome would become:
[
{"id":"1","random":"sadasd","mergethis":"Ding"},
{"id":"2","random":"assdfsadf","mergethis":"Ding,Flop,Bips"},
{"id":"3","random":"sdfss","mergethis":"Flung,Rorg"},
{"id":"4","random":"asdasdddaf","mergethis":"Shwung"}
]
I'm trying to iterate trough $products
and compare the values but I'm stuck at comparing the value to a subvalue of the array in stead of to the entire array
foreach($products as $key => $value){
if (in_array($value->id, $products)) {
//Delete this item and add product_category comma sepereated to first item
//unset($products[$key]);
}
}
This obviously doesn't work because it compares the item to the entire array in stead of to the sub value id
of the array item.
How do I go about getting my expected outcome?
Do I need to create a new array filled with the keys and id
values of each array item and iterate trough that? Or is there an easier method to compare object values inside an array to each other?