如何获得foreach循环的总和?

时间:2019-02-12 03:17:15

标签: php

我有一个foreach循环问题,我认为我的逻辑有些问题。表中的数据将从付款金额中扣除,如果付款金额为0,则会停止循环。

PHP 5

$payment_amount_pay = 5000;

foreach ($data as $value) {

    $amount = $value['AMOUNT'];

    $payment_amount_pay = $payment_amount_pay - $amount;


    echo $payment_amount_pay;

}

我表中的数据

2000
15000
3000

我总是得到这个输出

3000
-12000
-15000

这应该是正确的输出。

-2000
-3000

3 个答案:

答案 0 :(得分:1)

我相信您希望它像这样吗?

$payment_amount_pay = 5000;

foreach ($data as $value) {

    // Check if the amount already used up
    if($payment_amount_pay < 0) {
        break;
    }

    $amount = $value['AMOUNT'];

    // Get the differences
    $payment_amount_pay = $payment_amount_pay - $amount;

    if($payment_amount_pay >= 0) {
        // Changed to negative (not sure why you need it)
        echo 0  - $amount."<br>";
    }
    else {
        // Changed to negative (not sure why you need it)
        echo 0  - $payment_amount_pay - $amount."<br>";
    }
}

答案 1 :(得分:0)

我认为您要实现的目标是

   $payment_amount_pay = 5000;

foreach ($data as $value) {

    $amount = $value['AMOUNT'];
If ($payment_amount_pay -= amount > 0){
    $payment_amount_pay = $payment_amount_pay - $amount;}


    echo “-“.$amount;

}

答案 2 :(得分:0)

2000、15000、3000 ,我认为该金额代表$value['AMOUNT']

$payment_amount_pay = 5000;

    foreach ($data as $value) {

        $amount = $value['AMOUNT'];

        $payment_amount_pay = $payment_amount_pay - $amount;

        // first loop => 3000  = 5000 - 2000;  3000 will be $payment_amount_pay
        // second loop => -12000  = 3000 - 15000; -12000 will be $payment_amount_pay
        // third loop =>  -15000  = -12000 - 3000; -15000 will be $payment_amount_pay

        echo $payment_amount_pay;

    }

如何成为-2000和-3000?