从PHP中每次迭代Foreach中减少一个值

时间:2014-07-22 07:22:45

标签: php arrays foreach

我正在尝试从数组中兑换一个值。例如,我有20 Points,我将从获得积分列表中兑换。

这是我的数组结构,如下所示

$newstructure = array(
array('earnedpoints'=>'10','usedpoints'=>'0'),
array('earnedpoints'=>'25','usedpoints'=>'0'),
);

具有n个数据(数组)。

我正在尝试从获得的积分中减少值

Points to redeem : 20。在foreach声明中,我只是

$remainingpoints=20; // Redeeming Points is named as in variable of $remainingpoints
foreach ($newstructure as $keys => $newone) {

        if ($remainingpoints > $newone['earnedpoint']) {

            $remainingpoints = $remainingpoints - $newone['earnedpoint'];

        } else {
            $remainingpoints = $newone['earnedpoint'] - $remainingpoints;

        }


}

对于foreach获得点的第一次迭代的Point Redeeming为10,剩余点为10(基于上面的代码),使用的点为10

对于第二次迭代,获得的积分是25,但我想只兑换10,所以我想在兑换值完成后停止循环(上一个迭代10和当前迭代10)< / p>

我尝试将结果设为(Redeem Point 20

First Iteration Used Points 10 and Remaining Points is 10.
Second Iteration Used Points 10 and Remaining Points is 0.

此外,我也试图以数组的形式存储信息。

 $newstructure = array(
    array('earnedpoints'=>'10','usedpoints'=>'10','remainingpoints'=>'10'),
    array('earnedpoints'=>'25','usedpoints'=>'10','remainingpoints'=>'0'),
    );

有人能指出一个正确的方向以获得这个理想的结果吗?

1 个答案:

答案 0 :(得分:1)

首先,在一个地方,您使用earnedpoints作为表格密钥,然后在循环中使用earnedpoint

此代码适用于您:

<?php


$newstructure = array(
array('earnedpoints'=>'10','usedpoints'=>'0'),
array('earnedpoints'=>'25','usedpoints'=>'0'),
);


$remainingpoints=25; // Redeeming Points is named as in variable of $remainingpoints
foreach ($newstructure as $keys => $newone) {

        if ($remainingpoints  > $newone['earnedpoints']) {
            $toRedeem = $newone['earnedpoints'];            
        }
        else {
            $toRedeem =  $remainingpoints;
        }

        $remainingpoints -= $toRedeem; 

        $newstructure[$keys]['usedpoints'] = $toRedeem;
        $newstructure[$keys]['remainingpoints'] = $remainingpoints;

        /*
        if ( $remainingpoints == 0 ) {
            break;
        }
        */
}


var_dump($newstructure);

在评论中,我将代码放在您可能会破坏循环的位置,但是当您破解它时,您不会为以下数组值设置used_pointsremainingpoints