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

PHP数组连续递减运算:金额清零规则问题求助

债务递减运算问题

原始数据

#    amount   deduction
[0]   50        10
[1]   300       20
[2]   200       30

运算需求

  • 若前一项金额变为0,其扣除额(deduction)需累加到下一项的扣除额中;
  • 若中间项金额为0,前序所有扣除额累加至后项;
  • 若最后一项金额先于前项变为0,其扣除额需累加到倒数第二项的扣除额中。

预期运算过程

[0]          [1]          [2]
50  - 10     300 - 20     200 - 30
40  - 10     280 - 20     170 - 30
30  - 10     260 - 20     140 - 30
20  - 10     240 - 20     110 - 30
10  - 10     220 - 20      80 - 30
 0           200 - 30      50 - 30
             170 - 30      20 - 30
             140 - 30       0 -  0
             110 - 60
              50 - 60
               0

当前实现代码

$data = json_decode($debtsData, true);
$continue = true;
while($continue) {
    $continue = max(array_column($data, 'amount')) > 0;
    for($i=0; $i<count($data); ++$i) {
        $totalInterest = $data[$i]['interest_rate'] / 100;
        $periods = 12;
        $monthly = $data[$i]['monthly'];
        $_new_balance = !isset($data[$i]['done']) ? max($data[$i]['amount'], 0) : '';
        $interestPayment = ($totalInterest / $periods ) * $_new_balance;

        if($data[$i]['amount'] <= 0 && !isset($data[$i]['done'])) {
          $data[$i]['done'] = true;
          if(isset($data[$i+1])) {
             $data[$i+1]['monthly'] += $data[$i]['monthly'];
          }
        }

        echo !isset($data[$i]['done']) ? '$'.number_format(max($data[$i]['amount'], 0),2) : '';
        echo !isset($data[$i]['done']) ? '$'.number_format($data[$i]['monthly'],2) : '';
        echo !isset($data[$i]['done']) ? '$'.number_format($interestPayment,2).' ' : '';

        $data[$i]['amount'] -= $data[$i]['monthly'] - $interestPayment ;
     }
}

存在的问题

当前代码仅处理了前项金额为0时将扣除额累加至后项的场景,当最后一项金额先于倒数第二项变为0时,无法将最后一项的扣除额累加到倒数第二项的扣除额中。(注:无需关注代码中的利息相关变量)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:52:46