【发布时间】:2014-02-17 21:29:33
【问题描述】:
你如何在 foreach 循环中计算 (sum) + 一个值?
我正在开发一个板球应用程序,我必须每 6 次计算循环,然后计算特定值,然后回显总数。
我有一个不准确的代码,但类似这样。
并且有两个值:
- 球 $balls['1'];像 1,2,3,4,5 和多达 300-1000 个球的阵列
- 运行 $balls['6'];像 2,3,1,5 随机数这样的数组可以是任意的;
- 值来自 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,纠正问题格式