合并两个拉拉维尔收藏,保留原始密钥



我有以下两个集合:

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。

谢谢,朱利安

您可以使用

Laravel Collection的union()方法。请注意,在处理重复键时,这与merge()的行为不同:如果$array1$array2中都存在相同的键,并且您$merged = $array1->union($array2),则$array1的值将最终出现在$merged集合中,而$array2的值将被丢弃(Laravel联合文档(。

我会尝试使用字符串键进行合并和合并集合。从 laravel 文档部分集合中,函数 merge((

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

最新更新