-3

假设我有一个带有数值的数组。

$expenses = array(10, 10, 10, 10, 5, 5, 2, 20);

以及在循环内更改的数值。假设这个值被称为 $sub 并被初始化为 30。

我想要的是在下面的嵌套循环中从 $sub 中减去费用数组的每个值。

例如:

for($i = 0; $i < 50; $i++){

//$sub = a whatever value; 

    for($j = 0; $j < count($expenses); $j++){

       if ( $expenses[$j] > 0 ){
            //the area for calculations to run
           $expenses[$j] = $sub - $expenses[$j];
         }
     }
 }

结果是:

Index 0: $expenses[0] = $sub - $expenses[0]; // 30-10=20

Index 1: $expenses[1] = $sub - $expenses[1]; // 30-10=20

...

当嵌套循环发现当前数组值前一个不同时

(即 $expenses 数组中的索引 4 和索引 3),那么 $sub 必须具有循环中最后发生的减法的值,即 20。当这是真的时,主减法必须是 20-5。

虽然当前数组值与前一个相同,然后继续做 20-5 的事情。所以要记住减法的结果并调整 $sub 以便使用$expenses数组值进行减法。当减法的结果为负或为零时,必须终止执行。

在我们的例子中,第一个循环结束执行后的最终结果是:

指数0:30-10=20

指数一:30-10=20

指数2:30-10=20

指数3:30-10=20

指数4:20-5=15

指数5:20-5=15

指数6:15-2=13

指数7:13-20=-7

所以我想更新数组和减法值。

4

1 回答 1

2

所有你需要的是 :CachingIterator

$ci = new CachingIterator(new ArrayIterator($expenses));
foreach($ci as $k => $item) {
    $diff = $sub - $item;
    printf("Index %d: %d-%d = %d\n", $k, $sub, $item, $diff);
    if ($item != $ci->getInnerIterator()->current()) {
        $sub = $diff;
    }
}

输出

Index 0: 30-10 = 20
Index 1: 30-10 = 20
Index 2: 30-10 = 20
Index 3: 30-10 = 20
Index 4: 20-5 = 15
Index 5: 20-5 = 15
Index 6: 15-2 = 13
Index 7: 13-20 = -7

现场演示

于 2013-05-28T21:43:10.613 回答