我必须在表格内使用for循环制作菱形星号。 它必须在星号前后具有“空白”的<td>
空间,以使其居中居中,因此它看起来像一颗菱形。我怎么做? (我在HTML代码中使用了PHP。)
没有<tr>
和<td>
标记的代码,它看起来像菱形,因为它居中对齐:
<center>
<?php
echo "<table border = 1>";
// loop for the pyramid
for($i = 1; $i <= 10; $i += 2) {
for($j = 1; $j <= $i; $j++) {
echo "* ";
}
echo "<br />";
}
// loop for the inverted pyramid, so it looks like a diamond
for($i = 7; $i >= 1; $i -= 2) {
for($j = 1; $j <= $i; $j++) {
echo "* ";
}
echo "<br />";
}
echo "</table>";
?>
</center>
带有
<tr>
和<td>
标记的代码,需要“空格”以使其看起来像居中对齐:<?php
echo "<table border = 1>";
// loop for the pyramid
echo "<tr>";
for($i = 1; $i <= 10; $i += 2) {
echo "<tr>";
for($j = 1; $j <= $i; $j++) {
echo "<td>* </td>";
}
echo "</tr>";
}
echo "</tr>";
// loop for the inverted pyramid, so it looks like a diamond
for($i = 7; $i >= 1; $i -= 2) {
echo "<tr>";
for($j = 1; $j <= $i; $j++) {
echo "<td>* </td>";
}
echo "<br />";
echo "</tr>";
}
echo "</table>";
?>
请帮忙!
最佳答案
这是您的解决方案中的新代码。我添加了将空白td向前和向后*的逻辑
<?php
echo "<table border = 1>";
// loop for the pyramid
echo "<tr>";
$max = $initAmount = 10;
for($i = 1; $i <= $initAmount; $i += 2) {
$max = $max -2;
$halfTD = (int)$max/2;
echo "<tr>";
for($b = 1; $b <= $halfTD; $b++){
echo "<td></td>";
}
for($j = 1; $j <= $i; $j++) {
echo "<td>* </td>";
}
for($b = 1; $b <= $halfTD; $b++){
echo "<td></td>";
}
echo "</tr>";
}
echo "</tr>";
// loop for the inverted pyramid, so it looks like a diamond
$max = $initAmount = 10;
for($i = 7; $i >= 1; $i -= 2) {
$max = $max -2;
$diff = $initAmount - $max;
$blankTd = $diff/2;
echo "<tr>";
for($b = 1 ; $b <= $blankTd; $b++){
echo "<td></td>";
}
for($j = 1; $j <= $i; $j++) {
echo "<td>* </td>";
}
for($b = 1 ; $b <= $blankTd; $b++){
echo "<td></td>";
}
echo "</tr>";
}
echo "</table>";
?>
关于php - 如何在 table 内制作菱形图案/形状(星号)? (HTML + PHP),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40804926/