PHP如何对数组中相同tax_name项累加tax_price并保留其余字段
注意: 以下问题与类似问题逻辑接近,但需要适配当前场景的专属解决方案。
问题背景
现有如下结构的数组:
Array ( [0] => Array ( [tax_name] => VAT [tax_amount] => 3.000 [tax_type] => P [tax_price] => 15.44 [price_includes_tax] => Y ) [1] => Array ( [tax_name] => VAT [tax_amount] => 3.000 [tax_type] => P [tax_price] => 59.68 [price_includes_tax] => Y ) [2] => Array ( [tax_name] => VAT [tax_amount] => 3.000 [tax_type] => P [tax_price] => 1.86 [price_includes_tax] => Y ) [3] => Array ( [tax_name] => GST [tax_amount] => 3.300 [tax_type] => P [tax_price] => 2.11 [price_includes_tax] => N ) )
期望输出
需要按tax_name分组,累加同组的tax_price,同时保留其余字段:
Array ( [0] => Array ( [tax_name] => VAT [tax_amount] => 3.000 [tax_type] => P [tax_price] => 76.98 [price_includes_tax] => Y ) [1] => Array ( [tax_name] => GST [tax_amount] => 3.300 [tax_type] => P [tax_price] => 2.11 [price_includes_tax] => N ) )
现有实现问题
原有代码仅保留了tax_name和累加后的tax_price,丢失了其余字段:
$result = []; array_walk($_tax_array, function($item) use (&$result) { if (!isset($result[$item['tax_name']])) { $result[$item['tax_name']] = 0; } $result[$item['tax_name']] += $item['tax_price']; }); $resultFormated = []; foreach ($result as $key => $value) { $resultFormated[] = ['tax_name' => $key, 'tax_price' => $value]; } print_r($resultFormated);
上述代码输出结果:
Array ( [0] => Array ( [tax_name] => VAT [tax_price] => 76.98 ) [1] => Array ( [tax_name] => GST [tax_price] => 2.11 ) )
解决方案
实现逻辑为:以tax_name为分组键,首次遇到该税项时完整保存所有字段,后续同分组仅累加tax_price值,最后转为索引数组即可。
$result = []; array_walk($_tax_array, function($item) use (&$result) { $taxName = $item['tax_name']; if (!isset($result[$taxName])) { // 首次出现对应税种时直接保存完整字段 $result[$taxName] = $item; } else { // 已存在的税种仅累加tax_price $result[$taxName]['tax_price'] += $item['tax_price']; } }); // 转为从0开始的索引数组,匹配期望输出结构 $resultFormated = array_values($result); print_r($resultFormated);
内容的提问来源于stack exchange,提问作者Viira
相关产品推荐
相关产品推荐

