douwan7382 2019-02-01 22:58
浏览 154

使用put加入2个集合,并使用Laravel将两者的值保存在同一个键中

I have 2 quite simple collections (The first has 2 values within the array products and the second is a simple array):

$ collection_1 = collect ([
     'products' => [
         ['id' => 1, 'name' => 'Product 1'], ['id' => 2, 'name' => 'Product 2']
     ]
]);

$ collection_2 = collect ([
         ['id' => 4, 'name' => 'Product 4'], ['id' => 3, 'name' => 'Product 4']
]);

What I want to do is merge both collections using put (keeping the key products) but when using put I lose the values of the first collection and only get those of the second:

$collection_1->put('products', $collection_2);

Result:

{"products":[{"id":4,"name":"Product 4"},{"id":3,"name":"Product 4"}]}

How can I join both collections while maintaining the values both in the array "products"? This is the expected result:

{"products":[{"id":1,"name":"Product 1"},{"id":2,"name":"Product 2"},{"id":4,"name":"Product 4"},{"id":3,"name":"Product 4"}]}

Thanks

  • 写回答

1条回答 默认 最新

  • douchao1864 2019-02-01 23:36
    关注

    The put method just sets the value at the specified key, so it will overwrite what's there. If you want to keep all the values, merge the values from the first collection into the second.

    $collection_2->merge($collection_1->get('products'));
    

    Then you can use put like you're doing now.

    $collection_1->put('products', $collection_2);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料