foreach循环中的PHP计算,断点和重置值

时间:2014-02-17 21:29:34

标签: php loops foreach reset

如何计算(求和)+ foreach循环中的值?

我正在开发一个板球应用程序,我必须每6次计算一次循环,然后计算特定值,然后回显总数。

我的代码不完全但有类似的东西。

有两个值:

  1. Balls $ balls ['1'];数组如1,2,3,4,5和高达300-1000球
  2. 运行$ balls ['6'];数组如2,3,1,5随机数可以是任意的;
  3. 值来自mysql表列运行
  4. 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.但之后它没有显示确切的值

3 个答案:

答案 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;