【问题标题】:PHP Calculation, break point, and reset value in foreach loopforeach循环中的PHP计算、断点和重置值
【发布时间】:2014-02-17 21:29:33
【问题描述】:

你如何在 foreach 循环中计算 (sum) + 一个值?

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

我有一个不准确的代码,但类似这样。

并且有两个值:

  1. 球 $balls['1'];像 1,2,3,4,5 和多达 300-1000 个球的阵列
  2. 运行 $balls['6'];像 2,3,1,5 随机数这样的数组可以是任意的;
  3. 值来自 mysql 表列 balls 和 runs
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 来说,这样的东西可以正常工作。但之后它不会显示确切的值

【问题讨论】:

  • 对于我们这些不了解板球的人,您能否展示示例输入数据和所需的输出?
  • $runs = $ball + $ball 与 $runs = 2 * $ball 相同。这不是一个运行总数,您每次循环都会重置它。
  • 对不起,我是新来的,我编辑了问题以添加更多 desc,但代码格式现在令人困惑。是的,我想我正在重置它,所以我如何在 if($coundball == 6) echo $runs 之后重置下一个循环的值并为接下来的 6 个循环重置?
  • 感谢@Barmar,纠正问题格式

标签: php loops foreach reset


【解决方案1】:

您忘记重置 $countball。

您可以将 if 部分更改为:

if($countball == 6)
{ 
    echo $runs;
    $countball = 0; 
}

【讨论】:

  • 是的,但这不是问题,问题在于 $runs 计数!
  • 也设置$runs = 0。
【解决方案2】:

也许这就是你需要的:

$runs = 0;
foreach( $balls as $ball ){
    $runs += $ball['runs'];
}
echo $runs;

【讨论】:

  • 不起作用,请告诉我如何简单地将 foreach 值相加,例如当前循环中的值与下一个循环中的值相加?
  • 你还没有解释清楚你想要的结果是什么。
  • 我只想将当前 $ball['runs'] 与下一个循环 $ball['runs']; 相加示例结果是:1. 詹姆斯 2 球 3 跑 2. 亚当 1 球 4 跑 3. 詹姆斯 1 球 5 跑最终结果我需要的是从 foreach 循环总共 12 次运行,只有我可以从另一个查询到 mysql。跨度>
【解决方案3】:

在上面的@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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2014-03-03
    • 2023-03-09
    相关资源
    最近更新 更多