在这里,我计算了孵育10天后存在的细菌总数.用户只需输入初始细菌数并返回结果.接下来我要做什么使我有些困惑.我现在的目标是在循环中执行此操作,该循环还会在Web上的表中生成输出
页面如下所示. 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时的输出: