php - PHP通过数组中的键获取值的总和
问题描述
我有波纹管阵列
Array
(
[0] => stdClass Object
(
[gross_weight] => 20.500
[net_weight] => 10.500
[product_id] => 1120280
)
[1] => stdClass Object
(
[gross_weight] => 20.500
[net_weight] => 10.500
[product_id] => 1120281
)
[2] => stdClass Object
(
[gross_weight] => 20.500
[net_weight] => 10.500
[product_id] => 1120281
)
[3] => stdClass Object
(
[gross_weight] => 20.500
[net_weight] => 10.500
[product_id] => 1120280
)
)
我想遍历这些记录并通过 product_id 获得总重量和净重量组的总和
我尝试了下面的代码,但无法从这里继续获取输出
foreach ($my_array as $my_array_data) {
$mark_product_id = $my_array_data->product_id;
$gross_weight_mt = $mrkgdata->gross_weight_mt;
$net_weight_mt = $mrkgdata->net_weight_mt;
}
我想要的输出是在新数组中获取每个产品 id 的总重量和净重量。
Array
(
[0] => stdClass Object
(
[gross_weight] => 41.000
[net_weight] => 21.000
[product_id] => 1120280
)
[1] => stdClass Object
(
[gross_weight] => 41.000
[net_weight] => 21.000
[product_id] => 1120281
)
)
解决方案
public function getGroupByData($data) {
$groups = array();
foreach ($data as $item) {
$key = $item['product_id'];
if (!array_key_exists($key, $groups)) {
$groups[$key] = array(
'id' => $item['product_id'],
'gross_weight' => $item['gross_weight'],
'net_weight' => $item['net_weight'],
);
} else {
$groups[$key]['gross_weight'] = $groups[$key]['gross_weight'] + $item['gross_weight'];
$groups[$key]['net_weight'] = $groups[$key]['net_weight'] + $item['net_weight'];
}
}
return $groups;
}
推荐阅读
- python - 在 Python 中检查一个数字是否可以表示为两个半素数之和
- excel - 将特定行从工作簿复制到 x 个新工作簿(每行一个),仅粘贴为格式/值
- angular - 具有内置自定义功能的 Angular excel 插件
- python - 使用 numpy.where 比较特定的数组项
- .net - 获取附加到 Windows Server 2019 的磁盘的序列号
- php - html5 下载和 php 下载无法在移动设备上运行
- dart - 从 api 将数据保存到 localStorage
- php - PHP多个foreach循环在数组中插入对象
- javascript - 更改复选框选中角度 4 上整行的颜色
- javascript - 我正在学习 php 和 mysql,我正在使用数组创建一个动态表单。抛出空查询警告