首页 > 解决方案 > 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

)
)

标签: phparraysjson

解决方案


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;
}

推荐阅读