Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging Two Laravel Collections keeping the original keys

Tags:

laravel-5

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

like image 961
user2197774 Avatar asked Feb 10 '17 00:02

user2197774


1 Answers

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).

like image 129
RB_ Avatar answered Sep 23 '22 14:09

RB_