循环数组将先前值添加到当前值

时间:2014-03-19 18:16:17

标签: php

我希望遍历一个数组,将前一个值添加到当前值。这是我最近的尝试,但没有输出所需的结果

$array = array(
    "myKeyName"   => 3,
    "anotherName" => 8,
    "aKeyName"    => 12,
    "keyName"     => 6,
    "anotherKey"  => 34
    );

$setItems = array();

$i = 1;

foreach($array as $key => $val){
    $setItems['item'.$i] = $val+$val;
    $i++;
};

print_r($setItems);

输出

Array ( [item1] => 6 [item2] => 16 [item3] => 24 [item4] => 12 [item5] => 68 )

期望的输出

Array ( [item1] => 3 [item2] => 11 [item3] => 23 [item4] => 29 [item5] => 63 )

我明白为什么我得到当前的输出,我只是不知道如何改变它以获得有效的所需输出。有什么想法吗?

1 个答案:

答案 0 :(得分:4)

$array = array(
    "myKeyName"   => 3,
    "anotherName" => 8,
    "aKeyName"    => 12,
    "keyName"     => 6,
    "anotherKey"  => 34
    );

$setItems = array();

$i = 1;
$previous = 0;
foreach($array as $key => $val){
    $setItems['item'.$i] = $val+$previous;
    $previous += $val;
    $i++;
};