[英]Loop inside function in PHP
我知道这段代码是错误的,但它看起来应该与此接近,函数让我感到困惑
<body>
<table border="1">
<tr><th>i</th><th>square</th><th>cube</th></tr>
<?php
function square($x)
{
return $x * $x ;
}
function cube($y)
{
return $y * $y * $y ;
}
for ($i=1; $i <= 10 ; $i++)
echo "
<tr>
<td>$i</td>
<td>square('$i');</td>
<td>cube('$i');</td>
</tr>";
?>
</table>
</body>
函数调用没有正确连接:
<style>
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
</style>
<body>
<table style="border: 1">
<tr>
<th>i</th>
<th>square</th>
<th>cube</th>
</tr>
<?php
function square($x){
return $x * $x ;
}
function cube($y){
return $y * $y * $y ;
}
for ($i=1; $i <= 10 ; $i++)
echo "
<tr>
<td>$i</td>
<td>".square($i)."</td>
<td>".cube($i)."</td>
</tr>";
?>
</table>
</body>
你非常接近你想要的。 您应该更改“for”循环,以便您的代码最终看起来类似于以下几行:
<table border="1">
<tr><th>i</th><th>square</th><th>cube</th></tr>
<?php
function square($x) {
return $x * $x ;
}
function cube($y) {
return $y * $y * $y ;
}
for ($i=1; $i <= 10 ; $i++){
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo square($i); ?></td>
<td><?php echo cube($i); ?></td>
</tr>
<?php } ?>
</table>
欢迎使用 StackOverflow。 Majed 的答案是正确的,可能应该被标记为已接受的答案。 不过,我建议进行一些其他更改。
view.php
<style>
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
</style>
<body>
<table style="border: 1">
<tr>
<th>i</th>
<th>square</th>
<th>cube</th>
</tr>
<?php
foreach ($powers as $index => $power) {
echo "<tr><td>$index</td>";
foreach ($power as $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
?>
</table>
</body>
exponentHelpers.php
function square($x)
{
return $x * $x ;
}
function cube($y)
{
return $y * $y * $y ;
}
controller.php
require_once "exponentHelpers.php";
$base = 10;
$powers = [];
while($base--) { //Note, the self-decrementing short-hand will result in the values listed in reverse order.
//You could write it long-hand if you prefer, or call array_reverse() afterwards.
$powers[] = [
square($base),
cube($base),
];
}
require_once "view.php";
for ($i=1; $i <= 10 ; $i++) {
echo "
<tr>
<td>$i</td>
<td>".square($i)."</td>
<td>".cube($i)."</td>
</tr>";
}
幂函数:您使用square()
和cube()
函数重新发明了轮子。 PHP 提供了一个pow($base, $exponent)
函数来做同样的事情,并且不限于一个幂。 所以这可以完全取消exponentHelpers.php
部分。
符合 PSR2 的简写:如果您想使用它,完全是您的偏好,但是这里有两个 PHP 位您可能会感兴趣,查看view.php
部分中的循环。 一个是array_map()
,它允许在同一行上进行命令式数组循环和结果检索。 另一个是<?=
,它是<?php echo ...
HTML 模板简写。 把它们放在一起,你可以更简洁地展示你的循环:
<?= array_map(function (array $power, $index) {
//Newlines are optional. Just makes the output a little easier to read.
$powerElms = preg_replace("/^.*$/", "<td>$0</td>", $power);
return "<tr>\n<td>$index</td>\n" . implode("\n", $powerElms) . "</tr>\n";
}, $powers, array_keys($powers)) //Missing semicolon is not a typo. It's not needed with this syntax. ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.