[英]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.