这是我的随机数组,并不总是从2012年开始到2017年结束。
Array
(
[2012] => 1
[2014] => 1
[2015] => 1
[2016] => 4
[2017] => 1
)
我有一个这样的数组,我希望它像这样
Array
(
[2012] => 1 //The start, not add
[2014] => 2 //2012 + 2014 = 1 + 1 = 2
[2015] => 3 //2012 + 2014 + 2015 = 1 + 1 + 1 = 3
[2016] => 7 //2012 + 2014 + 2015 + 2016 = 1 + 1 + 1 + 4 = 7
[2017] => 8 //2012 + 2014 + 2015 + 2016 + 2017 = 1 + 1 + 1 + 4 + 1 = 8
)
答案 0 :(得分:1)
$arr = array(
2012 => 1, // 1
2014 => 1, // 2
2015 => 1, // 3
2016 => 4, // 7
2017 => 1 // 8
);
// Getting the all keys of array
$keys = array_keys($arr);
// Make a new array to set the executed values
$arr1 = array();
// loop the array
for ($i = 0; $i < count($arr); $i++) {
$sum = 0;
for ($j = 0; $j <= $i; $j++) {
$sum += $arr[$keys[$j]];
}
// set values to new array
$arr1[$keys[$i]] = $sum;
}
// print the new array
print_r($arr1);