如何计算(求和)+ foreach循环中的值?
我正在开发一个板球应用程序,我必须每6次计算一次循环,然后计算特定值,然后回显总数。
我的代码不完全但有类似的东西。
有两个值:
foreach( $balls as $ball ){
$countball++;
// here is what i need to know how do i calculate the values of $ball + $ball?
// so i can echo it inside the below if condition?
$runs = $ball['runs'] + $ball['runs']; // not working
if($countball == 6){
echo $runs;
}
$runs+= $ball; // reset the ball counting to continue addition from loop?
// and reset the
}// end foreach
然而这样的东西适用于第一个$ countball == 6.但之后它没有显示确切的值
答案 0 :(得分:0)
你忘了重置$ countball。
您可以将if部分更改为:
if($countball == 6)
{
echo $runs;
$countball = 0;
}
答案 1 :(得分:0)
也许这就是你所需要的:
$runs = 0;
foreach( $balls as $ball ){
$runs += $ball['runs'];
}
echo $runs;
答案 2 :(得分:0)
在上面的@Barmar的帮助下,我得到了如下所需的输出
$runs = 0;
$countball=0;
foreach( $balls as $ball ){
$countball++;
$runs += $ball['runs'];
if($countball == 6){
// reset runs from current loop runs for next, if i reset $runs = 0
// for some reason it does not (SUM) + this loops $ball['runs'] with last 5;
$runs = $ball['runs'];
$countball=0;
}// end if $countball == 6
}// end foreach
echo $runs;