我现在已经挣扎了一段时间,现在变得更加重要。
假设我们有一个值为
的数组Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
)
当我在foreach循环中循环此数组时,我想要第一个结果11秒结果36(11 + 25)第3个结果38(11 + 25 + 2)第4个结果45(11 + 25 + 2 +7)等。 ... 这样我得到累积结果
这是我到目前为止所尝试的:
<?php
foreach(array_slice(weeks($start_week), 0, 26) as $week):
$gewasregistratie["gezette_vruchten_cumulatief"][$week] = $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week] + $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week-1];
$gewasregistratie["gezette_vruchten_cumulatief"][$week] += $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week];
endforeach;
foreach(array_slice(weeks($start_week), 0, 26) as $week):
echo "<td week='".$week."' class='part1'>".$gewasregistratie["gezette_vruchten_cumulatief"][$week]."</td>";
endforeach;
foreach(array_slice(weeks($start_week), 26, 51) as $week):
echo "<td week='".$week."' class='part2'>".$gewasregistratie["gezette_vruchten_cumulatief"][$week]."</td>";
endforeach;
?>
有人可以帮助我朝正确的方向发展吗?
答案 0 :(得分:3)
简单就像煮鸡蛋一样。试试这段代码
$test = array(11,25,2,7);
$count = 0;
foreach($test as $i=>$k)
{
$count +=$k;
echo $count." ";
}
输出:
11 36 38 45
建议:您也可以将输出存储在另一个数组中。
答案 1 :(得分:2)
试试这个:
$a = array(11,25,2,7);
$c = 0;
foreach($a as $k=>$v){
$c += $v;
$b[] = $c;
}
print_r($b);
你将得到如下数组的结果:
数组([0] =&gt; 11 [1] =&gt; 36 [2] =&gt; 38 [3] =&gt; 45)
答案 2 :(得分:1)
最简单的方法
$original = array(23, 18, 5, 8, 10, 16);
$total = array();
$runningSum = 0;
foreach ($original as $number) {
$runningSum += $number;
$total[] = $runningSum;
}
var_dump($total);
答案 3 :(得分:0)
$array = array( 11, 25, 2, 7 );
$results = array();
foreach ($array AS $i => $v) {
if (empty($results)) {
$results[] = $v;
} else {
$results[] = $v + $results[$i - 1];
}
}
像这样。
答案 4 :(得分:0)
试试此代码
$arr=Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
);
$sum=0;
foreach($arr as $k=>$val)
{
echo "<br>".$sum+=$val;
}
答案 5 :(得分:0)
查找以下解决方案
$arr = array(11,25,2,7);
$sum =0;
foreach($arr as $val){
$sum +=$val;
echo $sum ."<br/>";
}
答案 6 :(得分:0)
如果您希望迭代一维数组,因为您的问题最初是措辞,array_map
将是您最有效的方法:
function cascade($n) {
static $current = 0;
return $current += (int) $n;
}
$test = array(11,25,2,7);
$result = array_map('cascade', $test);
/**
* You could also assign back to the original array like:
* $test = array_map('cascade', $test);
*/
如果您希望在多维数组中执行某些操作,那么使用array_walk
将成为解决方案。你想要一个例子吗?
答案 7 :(得分:-3)
试试这个。
$myArray = Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
);
$total = 0;
for($i=1; $i <= count($myArray); $i++) {
$total += $myArray[$i];
echo $total . ", ";
$cumulativeArray[] = $total;
}
print_r($cumulativeArray);