<?php
/**
* 金字塔生成器
* @param int $rows 行數 (1-20)
* @param bool $asc true正序/false倒序
* @return string HTML片段
*/
function fun_py($rows = 9, $asc = true) {
if ($rows < 1 || $rows > 20) return "行數必須在 1-20 之間";
if ($rows != (int)$rows) return '行數必須為整數';
$str = "";
$range = $asc ? range(1, $rows) : range($rows, 1);
foreach ($range as $i) {
$str .= '
';
// 前置空格
$spaces = $rows - $i;
$str .= str_repeat(' ', $spaces);
// 星號
$str .= str_repeat('* ', $i);
}
return $str;
}
echo fun_py(9, false); // 倒序 9 行
<?php
for ($a = 1; $a <= 10; $a++) {
// 空格: 10-$a 個
for ($b = 10; $b >= $a; $b--) echo " ";
// 星號: $a 個
for ($c = 1; $c <= $a; $c++) echo "* ";
echo "
";
}
<?php
for ($a = 10; $a >= 1; $a--) {
for ($b = 10; $b >= $a; $b--) echo " ";
for ($c = 1; $c <= $a; $c++) echo "* ";
echo "
";
}
| 層級 | 外層循環 | 空格數 | 星號數 |
|---|---|---|---|
| 正序第 i 行 | i = 1..n | n - i | i |
| 倒序第 i 行 | i = n..1 | n - i | i |
// 空心金字塔
for ($i = 1; $i <= $n; $i++) {
echo str_repeat(' ', $n-$i);
for ($j = 1; $j <= 2*$i-1; $j++) {
echo ($j==1 || $j==2*$i-1 || $i==$n) ? '* ' : ' ';
}
echo "
";
}
// 數字金字塔
for ($i = 1; $i <= $n; $i++) {
echo str_repeat(' ', $n-$i);
for ($j = 1; $j <= $i; $j++) echo "$j ";
for ($j = $i-1; $j >= 1; $j--) echo "$j ";
echo "
";
}
` 標籤包裹純文本
金字塔打印是循環控制、字符串拼接、邏輯思維的經典練習,掌握行數與字符數的數學關係即可舉一反三。