You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP按指定规格拆分数量逻辑异常,请求修正方案

修正PHP箱子拆分逻辑的问题

你的核心问题在于原代码采用了单纯的整除取余拆分,没有匹配你需求里的特殊规则——比如11-19的数量要直接用1个20规格箱子,以及剩余数量的处理逻辑。我们先明确你的需求规则,再给出修正后的代码:

需求规则梳理

从你的测试用例可以总结出以下逻辑:

  • 当数量在 11-19 之间:直接用1个20规格箱子
  • 当数量 ≥20:
    • 先算能装满的20规格箱子数,剩余部分如果≤10,用5规格箱子补(向上取整计算数量)
    • 剩余部分如果>10,则多拿1个20规格箱子(比如39,剩余19>10,直接用2个20)
  • 当数量 ≤10:用5规格箱子,数量为向上取整的结果(比如6→2个5,4→1个5)

修正后的代码

$pakingBoxType = [20, 5];
// 确保箱子类型按从大到小排序(这里已经是,可省略,但建议保留以防顺序变化)
rsort($pakingBoxType);
$product['quantity'] = 31;
$totalQty = $product['quantity'];
$arrBoxes = array_fill_keys($pakingBoxType, 0);

$largeBox = $pakingBoxType[0]; // 20规格
$smallBox = $pakingBoxType[1]; //5规格

if ($totalQty > 10) {
    if ($totalQty <= $largeBox) {
        // 11-19之间,直接用1个大箱子
        $arrBoxes[$largeBox] = 1;
    } else {
        // 计算基础大箱子数
        $largeCount = floor($totalQty / $largeBox);
        $remainder = $totalQty % $largeBox;
        
        if ($remainder > 10) {
            // 剩余部分超过10,多拿一个大箱子
            $largeCount++;
            $remainder = 0;
        }
        
        $arrBoxes[$largeBox] = $largeCount;
        
        if ($remainder > 0) {
            // 剩余部分用小箱子补
            $arrBoxes[$smallBox] = ceil($remainder / $smallBox);
        }
    }
} else {
    // 数量≤10,只用小箱子
    $arrBoxes[$smallBox] = ceil($totalQty / $smallBox);
}

// 输出结果
print_r($arrBoxes);

测试用例验证

我们逐个验证你的测试用例:

  1. 数量19:输出 Array ( [20] => 1 [5] => 0 ) ✔️
  2. 数量11:输出 Array ( [20] => 1 [5] => 0 ) ✔️
  3. 数量6:输出 Array ( [20] => 0 [5] => 2 ) ✔️
  4. 数量39:输出 Array ( [20] => 2 [5] => 0 ) ✔️
  5. 数量29:输出 Array ( [20] => 1 [5] => 2 ) ✔️

代码说明

  • 先对箱子类型排序,确保我们始终优先处理大规格(避免后续调整顺序出问题)
  • 分分支处理不同数量区间的逻辑,严格匹配你的测试用例需求
  • 用ceil()处理小箱子的数量,确保不足一个箱子的部分也用一个箱子装

内容的提问来源于stack exchange,提问作者Trushar Narodia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:52:33