2017-02-10 131 views
1

我有以下兩個集合:合併兩個Laravel集合保持原有鍵

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" 
    ] 
} 

使用Laravel的集合合併功能:

$merged = $ref_prod_containers->merge($ref_cust_prod); 
dd($merged); 

我得到如下:

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" 
    ] 
} 

不過,我希望保留原來的鑰匙。合併功能正在刪除它們並用0,1,2,3替換。

謝謝,朱利安

回答

3

您可以使用Laravel收集的union()方法。當心,這從merge()重複鍵打交道時表現不同:如果相同的密鑰是存在於$array1$array2,你去$merged = $array1->union($array2),那麼$array1值將$merged集合中結束,而$array2值將被丟棄(Laravel union documentation)。

+0

謝謝,這個伎倆。我的鑰匙是主鑰匙,所以我不需要擔心重複的鑰匙。 – user2197774

0

我會嘗試使用字符串鍵合併和合並集合。 從laravel文檔部分收藏,功能合併()

If the given array's keys are numeric, the values will be appended to the end of the collection: