如何按product_id分组子数组并执行条件算术运算?
按Product ID分组并执行条件算术运算的解决方案
看起来你需要对输入数组按product_id分组,然后根据moving_type的数值对product_number做动态的加减累计——我给你写个PHP的实现方案,刚好匹配你给出的数组格式:
核心实现思路
- 用一个结果数组来追踪每个
product_id的累计值 - 遍历输入数组的每一项,根据
moving_type判断是加还是减对应product_number - 处理前先检查当前
product_id是否已存在,不存在则初始化为0
完整代码示例
// 你的输入数组(这里补全了部分示例数据,你可以替换成自己的完整数组) $input = [ ['id' => 1, 'product_id' => 4, 'product_number' => 10, 'moving_type' => 1], ['id' => 2, 'product_id' => 4, 'product_number' => 3, 'moving_type' => 2], ['id' => 3, 'product_id' => 5, 'product_number' => 7, 'moving_type' => 1], ['id' => 4, 'product_id' => 5, 'product_number' => 2, 'moving_type' => 1], ['id' => 5, 'product_id' => 4, 'product_number' => 5, 'moving_type' => 1] ]; // 初始化结果存储数组 $productTotals = []; foreach ($input as $entry) { $prodId = $entry['product_id']; $num = $entry['product_number']; $type = $entry['moving_type']; // 初始化未出现过的product_id的累计值为0 if (!isset($productTotals[$prodId])) { $productTotals[$prodId] = 0; } // 根据moving_type执行加减操作 if ($type === 1) { $productTotals[$prodId] += $num; } elseif ($type === 2) { $productTotals[$prodId] -= $num; } } // 输出原始分组结果 echo "原始分组累计结果:\n"; print_r($productTotals); // 可选:转换为更结构化的数组格式 $formattedResult = []; foreach ($productTotals as $id => $total) { $formattedResult[] = [ 'product_id' => $id, 'total_product_number' => $total ]; } echo "\n结构化结果:\n"; print_r($formattedResult);
运行结果说明
针对上面的示例输入,运行后会得到:
原始分组累计结果: Array ( [4] => 12 [5] => 9 ) 结构化结果: Array ( [0] => Array ( [product_id] => 4 [total_product_number] => 12 ) [1] => Array ( [product_id] => 5 [total_product_number] => 9 ) )
其中product_id=4的计算逻辑是:10(加)-3(减)+5(加)=12,product_id=5是7+2=9,完全符合你的需求。
内容的提问来源于stack exchange,提问作者Arka
相关产品推荐
相关产品推荐

