循环减法,可以根据用户输入支付发票

时间:2017-12-29 12:33:03

标签: php

我正在创建一个脚本,用于计算在给定的用户预算/输入中可以支付哪些发票。

在下面的场景中,我们有3张发票,总共5328.00,但是用户只想支付1000.该脚本应该将1000分配给发票,付款顺序不是。这里很重要因此,这个例子的基本思路是发票[1]将全额支付(523.00),发票[2]将获得500,到期3283 - 500。

我正在努力使用这段代码很长一段时间,我真的不知道如何相应地更新到期/付款金额。对于任何进一步的信息,不要犹豫,这似乎是一个非常简单的例子,但也许我过于复杂。结果应按原样显示在$ invoiceUpdate数组

$invoice = array();

$invoice['1']['id'] = 1;
$invoice['1']['total'] = 523.00;
$invoice['1']['due'] = 500.00;
$invoice['1']['paid'] = 23.00;

$invoice['2']['id'] = 2;
$invoice['2']['total'] = 3283.00;
$invoice['2']['due'] = 3283.00;
$invoice['2']['paid'] = 0.00;

$invoice['3']['id'] = 3;
$invoice['3']['total'] = 1545.00;
$invoice['3']['due'] = 1545.00;
$invoice['3']['paid'] = 0.00;


$userBalanceInput = 1000; // user input
$invoiceUpdate = array();

foreach($invoice as $i){
     $left = $userBalanceInput - $i['due'];
     if($left > 0){
         // fully paid
          echo "INV".$i['id']." Total : ".$i['total']. " Due : ".$i['due']. " Paid : ".$i['paid']. " LoopLeft : ".$left." STATUS : Paid \n";
          $invoiceUpdate[] = array(
              'id' => $i['id'],
              'newDue' => '?',
              'newPaid' => 0 + $i['paid'], // calculate newPaid and add the old Paid value
              'oldTotal' => $i['total']
          );
     }
      if($left < 0){
          // partialy paid or not affected
          echo "INV".$i['id']." Total : ".$i['total']. " Due : ".$i['due']. " Paid : ".$i['paid']. " LoopLeft : ".$left." STATUS : UNPAID \n";
          $invoiceUpdate[] = array(
              'id' => $i['id'],
              'newDue' => '?',
              'newPaid' => 0 + $i['paid'], // calculate newPaid and add the old Paid value
              'oldTotal' => $i['total']
          );
      }
     // $userBalanceInput = $left;

}

var_dump($invoice);
echo "---------";
var_dump($invoiceUpdate);

MCVE http://sandbox.onlinephpfunctions.com/code/c09805db45c4dd241e16a9db5061ba57b7051b93

提前致谢

1 个答案:

答案 0 :(得分:1)

在这个简单的情况下,没有给出任何薪酬逻辑(支付很多发票,先支付最早的,先支付bigest,......),你可以简单地循环发票并计算你可以支付的剩余金额。

$invoiceUpdate = array_map(function($item) use (&$userBalanceInput) {
    $newItem = ['id' => $item['id']];
    $amount = $userBalanceInput > $item['due'] ? $item['due'] : $userBalanceInput;
    $userBalanceInput -= $amount;

    return [
        'id' => $item['id'],
        'newDue' => $item['due'] - $amount,
        'newPaid' => $item['paid'] + $amount,
        'oldTotal' => $item['total']
    ];
}, $invoice);