First, let me apoligise for the picture. I know its not suppose to be posted like this.
Bellow I have two collections. I want to update the key->value pair in collection1
with the values in collection2
. Collection1
contains way more items including the ones in collection2
The keys in collection2
exist 100% in collection1
.
I have tried a few suggestions without success like
$updatedCollection = $collection1->map(function ($item) use ($collection2) {
$matchingItem = $collection2->where('id', $item['id'])->first();
if ($matchingItem) {
return array_merge($item, $matchingItem);
}
return $item;
});
and
$res = $collection1->map(function ($item) use ($collection2) {
$item = (array)$item;
$matchingItem = $collection2->where('id', $item['id'])->first();
if ($matchingItem) {
return array_merge($item, $matchingItem);
}
$itemZ[] = (object)$item;
$itemZZ = (object)$itemZ;
$itemZZZ = collect($itemZ);
return $itemZZZ;
});
But mostly I get a collection with the items
being an array where it should be an class and also the values arn’t updated.
I did not think it would be this tricky, but I cant seem to get it to return the same format as the original. and the update fails aswell.
4
Answers
you can use array merge and data_get
here’s a basic example
merging based on array1 collection items (array2 item values will overwrite array1 items);
merging based on array2 collection items (array1 item values will overwrite array2 items);
Also, post the actual result of the collection you are trying to merge,
you can get them by
or
I will try to answer this with example
This approach works with unique key (here id is unique)
Since you have 2 Collection, one could simply use
merge
of Collection to merge this 2 Collections together:https://laravel.com/docs/master/collections#method-merge
From the description
So, as far as I understand it, this is exactly what you want to get.
Because $matchingItem and $item are a class instance. To use array_merge, you need to convert them to array and to get object response, convert the result of array_merge to object