Continues Deduction using php

Please don’t judge I just need help with this.

I have this array values from the database

#    amount    monthly    interest rate
[0]   10,000    500           10%
[1]   400,000   12,000        5%

I want to have a recursive deduction of these arrays until data is zero, and then if the first amount of the array is zero(0) the deduction will add to the next data, until all amount will be zero (0).

Sample Calculation and my code

$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 ;
     }
}

My Output is Below

             [0]                           [1]    
Beginning - Monthly - Interest     Beginning  - Monthly  - Interest
10,000    - 500     -  83.33       400,000    - 12,000   - 1,666.67
9,583.33  - 500     -  79.86       389,666.67 - 12,000   - 1,623.61
9,163.19  - 500     -  76.36       379,290.28 - 12,000   - 1,580.38
8,739.55  - 500     -  72.83       368,870.65 - 12,000   - 1,536.96
...        ...         ...         ...          ...        ...
480.78    - 500     -  4.00       162,438.96  - 12,500   - 676.83
0           0       0        0    150,615.79  - 12,500   - 627.56
0           0       0        0    138,743.35  - 12,500   - 578.10
...        ...         ...         ...          ...        ...
0           0       0        0     0            0           0

What I was needed is that if the first data array has a remaining monthly (e.g above is 500) and it only deducted from the amount 484.78 the remaining should be deducted as well on the second data of the array. And I also confused on how to do it if the first array is much bigger than the second data. If it is vice versa and the second array is already zero(0) the monthly should be added on the first data of the array.