将 2d Laravel 集合按两列分组,并对每组内的第三列求和

问题描述 投票:0回答:2

我有这个收藏:

$stocks = collect(
    [
        ['sku' => '123', 'batch' => '123', 'qty_total' => 1],
        ['sku' => '1233', 'batch' => '123', 'qty_total' => 2],
        ['sku' => '123', 'batch' => '123', 'qty_total' => 3],
        ['sku' => '5', 'batch' => '123', 'qty_total' => 4],
    ]
);

我需要像这样进入输出集合:

[
        ['sku' => '123', 'batch' => '123', 'qty_total' => 4],
        ['sku' => '1233', 'batch' => '123', 'qty_total' => 2],
        ['sku' => '5', 'batch' => '123', 'qty_total' => 4],
    ]

我正在将集合分组为

$coll = $coll
    ->groupBy(['sku','batch'], true)

但我不明白接下来我必须如何求和。

php laravel sum grouping laravel-collection
2个回答
1
投票

你可以这样做:

  $stocks = collect(
   [
      ['sku' => '123', 'batch' => '123', 'qty_total' => 1],
      ['sku' => '1233', 'batch' => '123', 'qty_total' => 2],
      ['sku' => '123', 'batch' => '123', 'qty_total' => 3],
      ['sku' => '5', 'batch' => '123', 'qty_total' => 4],
   ]
  );

return $stocks->groupBy(['sku','batch'], true)->map(function($items){
  $firstItem = $items->values()->first();

  return collect($firstItem->first())->merge([
    'qty_total' => $firstItem->sum('qty_total')
  ]);
})->values();

0
投票

将 2 元素数组输入到

groupBy()
方法只会产生更多工作/处理,因为 它会生成不必要的深层结构。 请注意 Mohammad 的片段如何重新索引 (
values()
),然后调用
first()
,然后调用
first()
才能遍历到所需的级别。

相反,提供

groupBy()
一个回调函数以形成“复合字符串键”并保持分组数据浅。

代码:(PHPize演示

var_export(
    $stocks
    ->groupBy(fn($row) => $row['sku'] . '_' . $row['batch'])
    ->map(fn($set) => array_merge($set->first(), ['qty_total' => $set->sum('qty_total')]))
    ->values()
    ->toArray()
);

输出:

array (
  0 => 
  array (
    'sku' => '123',
    'batch' => '123',
    'qty_total' => 4,
  ),
  1 => 
  array (
    'sku' => '1233',
    'batch' => '123',
    'qty_total' => 2,
  ),
  2 => 
  array (
    'sku' => '5',
    'batch' => '123',
    'qty_total' => 4,
  ),
)

主题相关内容:

© www.soinside.com 2019 - 2024. All rights reserved.