Reputation: 501
I have the following two collections:
Collection {#402 ▼
#items: array:1 [▼
4007 => "4007 - Container Deposit - 18.00 Drum - In Stock: 0.00"
]
}
Collection {#398 ▼
#items: array:3 [▼
1000 => "1000 - Acetone - 162.00 KG - In Stock: 10000.00"
1001 => "1001 - Acetone - 15.80 KG - In Stock: 0.00"
24662 => "24662 - 1L Untd Antifreeze Orange FO2272A60(Prem - 1.00 Litre - In Stock: 0.00"
]
}
Using Laravel's collection merge function:
$merged = $ref_prod_containers->merge($ref_cust_prod);
dd($merged);
I get the following:
Collection {#397 ▼
#items: array:4 [▼
0 => "4007 - Container Deposit - 18.00 Drum - In Stock: 0.00"
1 => "1000 - Acetone - 162.00 KG - In Stock: 10000.00"
2 => "1001 - Acetone - 15.80 KG - In Stock: 0.00"
3 => "24662 - 1L Untd Antifreeze Orange FO2272A60(Prem - 1.00 Litre - In Stock: 0.00"
]
}
However I wish to retain the original keys. The merge function is removing them and replacing with 0,1,2,3.
Thanks, Julian
Upvotes: 14
Views: 28616
Reputation: 799
You can use Laravel Collection's union()
method. Beware that this behaves differently from merge()
when dealing with duplicate keys: if the same key is present in both $array1
and $array2
and you go $merged = $array1->union($array2)
, then the value of $array1
will end up in the $merged
collection, and the value of $array2
will be discarded (Laravel union documentation).
Upvotes: 35
Reputation: 9161
I would try to use string keys for the merging and merged collection. From the laravel docs section collections, function merge()
If the given array's keys are numeric, the values will be appended to the end of the collection:
Upvotes: 0