PHP实现按目标价格数组分组匹配多维数组元素的问题
解决方案
首先,你的问题出在累加过程中没有持续收集参与求和的元素,而是仅记录了每组的最后一个元素。以下是修正后的代码,同时处理了浮点数精度问题(避免因浮点运算误差导致判断失败):
$line_items = [ 0 => ['price' => 41.99, 'id' => 12, 'quantity' => 1], 1 => ['price' => 155.95, 'id' => 11, 'quantity' => 1], 2 => ['price' => 21, 'id' => 13, 'quantity' => 1] ]; $price_array = [ 0 => 197.94, 1 => 21.00 ]; $result = []; $itemIndex = 0; // 跟踪line_items的当前处理位置 $totalItems = count($line_items); foreach ($price_array as $targetPrice) { $currentGroup = []; $currentSum = 0.0; // 循环累加元素直到达到目标价格(或处理完所有元素) while ($itemIndex < $totalItems && abs($currentSum - $targetPrice) > 0.0001) { $item = $line_items[$itemIndex]; $currentSum += $item['price']; $currentGroup[] = $item; // 将当前元素加入分组 $itemIndex++; } // 仅当分组非空时加入结果(避免因目标价格不匹配导致的空分组) if (!empty($currentGroup)) { $result[] = $currentGroup; } } // 输出结果 print_r($result);
代码说明
- 指针跟踪:用
$itemIndex记录当前处理到line_items的哪个元素,确保处理完一组后继续处理下一组,不会重复使用元素。 - 临时分组收集:每个目标价格对应一个
$currentGroup,累加过程中把每个参与的元素都加入这个临时数组,而不是只保存最后一个。 - 浮点数精度处理:用
abs($currentSum - $targetPrice) > 0.0001代替直接相等判断,避免因PHP浮点数运算的精度误差导致判断失败(比如0.1 + 0.2不等于0.3的情况)。
预期输出
Array ( [0] => Array ( [0] => Array ( [price] => 41.99 [id] => 12 [quantity] => 1 ) [1] => Array ( [price] => 155.95 [id] => 11 [quantity] => 1 ) ) [1] => Array ( [0] => Array ( [price] => 21 [id] => 13 [quantity] => 1 ) ) )
你之前代码的常见问题
通常出现“仅保留每组最后一个元素”的情况,是因为你在累加时没有用数组追加([]=),而是直接用赋值($currentGroup = $item)覆盖了之前的元素,导致每次只保留最后一个加入的元素。修正时只需要把赋值改为追加即可。
内容的提问来源于stack exchange,提问作者BoogaBooga
相关产品推荐
相关产品推荐

