php - php 中每天细菌计数的输出循环

标签 php loops for-loop

在这里,我计算了培养 10 天后存在的细菌总数。用户只需输入初始细菌的数量并返回结果。我接下来要做的事情让我有些困惑。我现在的目标是在一个循环中执行此操作,该循环还会在网络上的表格中生成输出 页面如下图。 x代表当天细菌总数。有谁知道如何在 php 中执行此操作?

Initial Bacteria present:
Day: Bacteria:
1      x
.      x
.      x
.      x
10     x

这是我用于计算的 php/html。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>  
<?php 
if(isset($_POST['submit'])) {
$x = (int)$_POST['initialBacteria'];
$days = 10;
$total = $x * pow(2, $days);
echo "There are: ", $total, " bacterium present in the culture after 10 days of incubation."; }     
//loop goes here
?>
<!DOCTYPE html>
<html>
<head>
<link href="style/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div align="center" id="main">
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
      Initial Bacterium:<input class="text" name="initialBacteria" type="text" size="15"><br><br>
      <input class="text" type="submit" name="submit" value="Calculate" />
  </form>      
<hr>
</div>
</body>
</html>

最佳答案

您可以遍历这些天,然后将结果插入数组。

将数据插入数组后,您可以使用 foreach 循环来回显数组中的每个结果。

<?php 
if(isset($_POST['submit'])) {
    $x = (int)$_POST['initialBacteria'];
    $days = 10;

    $total = array();
    for ($i=1; $i <= $days; $i++) { 
        $total[$i] = $x * pow(2, $i);
    }

    foreach ($total as $totalKey => $totalValue) {
        echo "There are: ", $totalValue, " bacterium present in the culture after ".$totalKey." days of incubation.<br />";
    }
}
 ?>

这是我在 $x 的值中输入 30 时的输出: enter image description here

关于php - php 中每天细菌计数的输出循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31237327/

相关文章:

loops - 如何在不运行以下脚本的情况下退出循环

javascript - 使用 JQuery 隐藏和显示

c++ - 基于范围的 for 循环,第一项的特殊情况

php - Laravel:无法向请求添加参数

java - 使用 Java Servlet 读取和写入以太网端口的替代方案

php - 如何在 symfony 路由中传递数组?

python - 在 Python 中使用 for 循环垂直翻转图像

php - Composer : Develop directly in vendor packages

javascript - 如何在 Javascript 中循环 JSON 响应以获取特定数据

c - 为什么每次循环迭代后 int 都会重置为零?