Home > Net >  Combine two collections without looping
Combine two collections without looping

Time:03-04

How can I combine two collections without using any of iterative collection methods?

I have the following:

$stores = collect([
    ['store_id'=> 5, 'name' => 'test1'],
    ['store_id'=> 33, 'name' => 'test2'],
    ['store_id'=> 7, 'name' => 'test3'],
]);

$estimations = [
    33 => ['minutes' => 40],
    5 => ['minutes' => 30],
    7 => ['minutes' => 25]
];

I want the result to be like:

[
    ['store_id'=> 5, 'name' => 'test1', 'minutes' => 30],
    ['store_id'=> 33, 'name' => 'test2', 'minutes' => 40],
    ['store_id'=> 7, 'name' => 'test3', 'minutes' => 25],
]

without using any iterative methods like transform or map.

CodePudding user response:

Assuming the keys in the $estimations array are supposed to correspond to the store_id value in the collection, I think you can use replaceRecursive() if you key the collection by store_id.

$result = $stores->keyBy('store_id')->replaceRecursive($estimations)->values();

CodePudding user response:

You can use merge() method from Laravel Collection's.

$collection = collect(['product_id' => 1, 'price' => 100]);

$merged = $collection->merge(['price' => 200, 'discount' => false]);

$merged->all();

As said in the Laravel Docs: "If a string key in the given items matches a string key in the original collection, the given item's value will overwrite the value in the original collection".

Docs: https://laravel.com/docs/9.x/collections#method-merge

  • Related