【问题标题】:Merging the values of a Collection in Laravel在 Laravel 中合并集合的值
【发布时间】:2020-01-25 04:15:44
【问题描述】:

我一直在考虑这个问题。到目前为止,我尝试的是阅读、搜索和尝试 Collections 的文档,但对我正在尝试做的事情没有运气。

我想要实现的是通过“product_id”合并所有产品,对“qty”求和,并将同一产品的一组“责任”放入一个新集合中:

我的数据库中有以下信息:

[
   {
      "qty":"8",
      "product_id":6,
      "product":{
         "id":6,
         "name":"Mantequilla",
         "barcode":"123456789",
         "full_name":"Mantequilla - 123456789"
      },
      "itbis":"0",
      "precio":"0",
      "responsible":"Juan"
   },
   {
      "qty":"4",
      "product_id":6,
      "product":{
         "id":6,
         "name":"Mantequilla",
         "barcode":"123456789",
         "full_name":"Mantequilla - 123456789"
      },
      "itbis":"0",
      "precio":"0",
      "responsible":"Carlos"
   },
   {
      "qty":"3",
      "product_id":8,
      "product":{
         "id":8,
         "name":"Papas",
         "barcode":"4567894456",
         "full_name":"Papas - 4567894456"
      },
      "itbis":"0",
      "precio":"0",
      "responsible":"Pedro"
   }
]

然后会被转换成这样:

[
   {
      "qty":"12",
      "product_id":6,
      "product":{
         "id":6,
         "name":"Mantequilla",
         "barcode":"123456789",
         "full_name":"Mantequilla - 123456789"
      },
      "itbis":"0",
      "precio":"0",
      "responsible": ["Juan", "Carlos"]
   }
   {
      "qty":"3",
      "product_id":8,
      "product":{
         "id":8,
         "name":"Papas",
         "barcode":"4567894456",
         "full_name":"Papas - 4567894456"
      },
      "itbis":"0",
      "precio":"0",
      "responsible":"Pedro"
   }
]

【问题讨论】:

    标签: php arrays laravel eloquent


    【解决方案1】:
            $arr = [...]; // Your input array
    
            $res = collect($arr)
                ->groupBy('product_id')
                ->map(function ($sub_collection) {
                    $first = $sub_collection->first();
    
                    $first['qty']         = array_sum(array_column($sub_collection->toArray(), 'qty'));
                    $first['responsible'] = array_merge(array_column($sub_collection->toArray(), 'responsible'));
    
                    return $first;
                })
                ->toArray();
    

    【讨论】:

    • 谢谢!你拯救了我的一天。我没有弄清楚地图的工作原理,所以我了解了它的工作原理并解决了我的问题。
    猜你喜欢
    • 2021-09-20
    • 2019-09-15
    • 2018-07-31
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2016-06-05
    • 2017-07-21
    相关资源
    最近更新 更多