简体   繁体   English

简单的 php 对于每个它都不能很好地相加

[英]simple php for each it is not adding sums well

there is 3 positions in $input['order_items'] , i am extracting $orderItem['subtotal'] which gives to me the total of a product and $orderItem['subtotal_tax'] which gives to me total tax of such product, what i am doing is adding subtotal with subtotal_tax , the problem is the function is not summing or adding correctly the value, for example in first position i got this: $input['order_items']中有 3 个位置,我正在提取$orderItem['subtotal']给我一个产品的总和$orderItem['subtotal_tax']给我这个产品的总税,我正在做的是用subtotal_tax添加subtotal计,问题是 function 没有正确地求和或添加值,例如在第一个 position 中我得到了这个:

"total": "13302",
      "total_tax": "0",

second position i got this:第二个 position 我得到了这个:

"total": "9711",
      "total_tax": "0",

third position i got this:第三个 position 我得到了这个:

"subtotal": "14022",
      "subtotal_tax": "0",

as result of the sum it should give to me this:作为总和的结果,它应该给我这个:

37035

but i am getting:但我得到:

28044

must ask, why?一定要问,为什么? and how to correct it?以及如何纠正它? thanks in foward感谢转发

$i = 0;
$nvCantVar = 0;
$subtotal = 0;
$subtotal_tax = 0;
$NotaVentaDetalleDTO = '';
foreach ($input['order_items'] as $orderItem) {
    $i++;

    $subtotal = $orderItem['subtotal'];
    $subtotal_tax = $orderItem['subtotal_tax'];
    $nvCantVar =  $subtotal + $subtotal_tax;  
}

$nvCantVar = $nvCantVar + $nvCantVar;

why could this be happening?为什么会这样?

You are using a scalar variable in the loop and therefore over writing the accumulator with the last value each time rather than accumulating a grand total.您在循环中使用标量变量,因此每次都用最后一个值覆盖累加器,而不是累加总计。

Instead of = use += to add each value to the existing value of the accumulator in the loop而不是=使用+=将每个值添加到循环中累加器的现有值

$nvCantVar = 0;

foreach ($input['order_items'] as $orderItem) {
    $nvCantVar +=  $orderItem['subtotal'] + $orderItem['subtotal_tax'];  
}

echo $nvCantVar;

Your PHP code isn't following the logic you want at all.您的 PHP 代码根本没有遵循您想要的逻辑。

Firstly why the $i what is this being used for?首先,为什么$i这是用来做什么的? Secondly your code is looping, overriding the value of $nvCantVar and then simply adding the final value of this variable to itself to get the new value.其次,您的代码正在循环,覆盖$nvCantVar的值,然后简单地将此变量的最终值添加到自身以获得新值。

So the math it is doing is:所以它正在做的数学是:

$nvCantVar = 14022 + 14022

What you want is something like你想要的是像

$nvCantTotal = 0;
foreach ($input['order_items'] as $orderItem) {
  $subtotal = $orderItem['subtotal'];
  $subtotal_tax = $orderItem['subtotal_tax'];
  $nvCantTotal += $subtotal + $subtotal_tax;  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM