Lets say I have a collection like
{
"object1": [
{
"name" xxx,
"size" 999
}
],
"object2": [
{
"name": yyy,
"size": 888,
}
]
}
And I have another collection like
{
"object2": [
{
"name" aaa,
"size" 111
}
],
"object3": [
{
"name": bbb,
"size": 222,
}
]
}
I would like to get a collection like
{
"object1": [
{
"name" xxx,
"size" 999
}
],
"object2": [
{
"name": yyy,
"size": 888,
},
{
"name" aaa,
"size" 111
}
],
"object3": [
{
"name": bbb,
"size": 222,
}
]
}
mergeRecursively works but it encapsulates the extra results in an "items" array which looks like this
{
"object1": [
{
"name" xxx,
"size" 999
}
],
"object2": {
"items": [
{
"name": yyy,
"size": 888,
},
{
"name" aaa,
"size" 111
}
]
],
"object3": [
{
"name": bbb,
"size": 222,
}
]
}
Any help is appreciated! Thanks!
You can use the Collection::each()
method to iterate through each item of one collection and build a replacement collection.
$results = new Collection;
$collection1->each(function($item, $key) use ($collection2, $results) {
$push = $collection2->has($key) ? $item->mergeRecursive($collection2->get($key)) : $item;
$results[$key] = $push;
});
dump($results);