【问题标题】:Output loop in php from a bacterium count per day每天细菌计数的 php 输出循环
【发布时间】:2015-09-23 02:19:36
【问题描述】:

在这里,我计算了孵化 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>

【问题讨论】:

  • 你试过什么?如果$total = $x * pow(2, $days); 为您提供$days 天的结果,那么从nn+1 天的计数如何变化?

标签: php loops for-loop


【解决方案1】:

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

将数据插入数组后,您可以使用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 />";
    }
}
 ?>

这是我将30 输入$x 的值时的输出:

【讨论】:

  • 我们走在正确的轨道上。我现在得到的是 Undefined index: initialBacteria in /home/user/public_html/index2.php on line 6
  • 当我提交时,通知消失了,但我仍然想知道如何删除它。
  • 哦,我忘了添加if(isset($_POST['submit'])) {} 我会编辑我的答案
猜你喜欢
  • 1970-01-01
  • 2011-02-17
  • 2019-09-11
  • 1970-01-01
  • 1970-01-01
  • 2015-08-07
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多