【问题标题】:Loop subtraction, which invoices can be paid based on user input循环减法,可以根据用户输入支付哪些发票
【发布时间】:2018-06-09 21:35:22
【问题描述】:

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

在下面的场景中,我们有 3 张发票,总计 5328.00,但用户只想支付 1000。脚本应该将 1000 分配给发票,付款顺序在这里并不重要。因此,此示例的基本理念是 invoice[1] 将获得全额付款 ( 523.00 ),invoice[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);

MCVEhttp://sandbox.onlinephpfunctions.com/code/c09805db45c4dd241e16a9db5061ba57b7051b93

提前致谢

【问题讨论】:

  • 你的问题到底是什么?
  • 如何获取newDue和newPaid值,不知道如何循环计算

标签: php


【解决方案1】:

在这个没有给出任何支付逻辑的简单案例中(支付多张发票,先支付最旧的,先支付最大的……),您可以简单地遍历发票并计算您可以支付的剩余金额。

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

【讨论】:

    猜你喜欢
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多