萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 實作九九乘法表:四種迴圈寫法與教學應用範例

前言

九九乘法表是程式入門經典練習,涵蓋巢狀迴圈、字串格式化、條件判斷、表格輸出等核心概念。本文提供四種 PHP 實作風格,從基礎到進階,適合教學示範與面試熱身。

版本一:經典雙層 for 迴圈(最直觀)

<?php
echo "<table border='1' cellpadding='5' cellspacing='0'>\n";
for ($i = 1; $i <= 9; $i++) {
    echo "  <tr>\n";
    for ($j = 1; $j <= 9; $j++) {
        $product = $i * $j;
        // 對齊:個位數前補空格
        $display = sprintf('%2d', $product);
        echo "    <td>$i × $j = $display</td>\n";
    }
    echo "  </tr>\n";
}
echo "</table>\n";

版本二:三角形輸出(避免重複,如 2×3 與 3×2 只顯示一次)

<?php
echo "<table border='1' cellpadding='5' cellspacing='0'>\n";
for ($i = 1; $i <= 9; $i++) {
    echo "  <tr>\n";
    for ($j = 1; $j <= $i; $j++) { // j <= i 只輸出左下三角
        echo "    <td>$j × $i = " . sprintf('%2d', $j * $i) . "</td>\n";
    }
    echo "  </tr>\n";
}
echo "</table>\n";

版本三:函數化與參數化(可複用、可測試)

<?php
/**
 * 產生乘法表 HTML
 *
 * @param int    $max       最大乘數(預設 9)
 * @param bool   $triangular true=三角形, false=完整方陣
 * @param string $tableClass CSS 類別
 * @return string HTML 字串
 */
function multiplicationTable(int $max = 9, bool $triangular = false, string $tableClass = 'multiplication-table'): string
{
    $html = ["<table class='$tableClass'>"];
    for ($i = 1; $i <= $max; $i++) {
        $html[] = "  <tr>";
        $end = $triangular ? $i : $max;
        for ($j = 1; $j <= $end; $j++) {
            $product = $i * $j;
            $html[] = "    <td>$i × $j = " . sprintf('%2d', $product) . "</td>";
        }
        // 三角形模式補齊空白欄位(可選)
        if ($triangular && $i < $max) {
            $html[] = str_repeat("    <td>&nbsp;</td>", $max - $i);
        }
        $html[] = "  </tr>";
    }
    $html[] = "</table>";
    return implode("\n", $html);
}

// 使用
echo multiplicationTable(9, false, 'full-table'); // 完整 9x9
echo multiplicationTable(9, true, 'tri-table');   // 三角形

版本四:現代化 - 產生 JSON 資料,前端 Vue/React 渲染

<?php
// api/multiplication.php
header('Content-Type: application/json; charset=UTF-8');

$max = (int)($_GET['max'] ?? 9);
$format = $_GET['format'] ?? 'grid'; // grid | triangular | flat

$data = [];
for ($i = 1; $i <= $max; $i++) {
    for ($j = 1; $j <= $max; $j++) {
        if ($format === 'triangular' && $j > $i) continue;
        $data[] = [
            'multiplicand' => $i,
            'multiplier' => $j,
            'product' => $i * $j,
            'expression' => "$i × $j = " . ($i * $j),
        ];
    }
}

echo json_encode([
    'max' => $max,
    'format' => $format,
    'count' => count($data),
    'data' => $data,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
<!-- 前端 Vue 3 範例 -->
<div id="app">
  <select v-model="max">
    <option v-for="n in 12" :value="n">{{ n }} × {{ n }}</option>
  </select>
  <label><input type="checkbox" v-model="triangular"> 三角形</label>

  <table class="table">
    <tr v-for="row in grouped" :key="row[0].multiplicand">
      <td v-for="cell in row" :key="cell.multiplier">
        {{ cell.expression }}
      </td>
    </tr>
  </table>
</div>

<script type="module">
import { createApp, ref, computed } from 'vue'
createApp({
  setup() {
    const max = ref(9)
    const triangular = ref(false)
    const data = ref([])

    async function load() {
      const res = await fetch(`/api/multiplication.php?max=${max.value}&format=${triangular.value ? 'triangular' : 'grid'}`)
      const json = await res.json()
      data.value = json.data
    }

    const grouped = computed(() => {
      const groups = {}
      data.value.forEach(cell => {
        if (!groups[cell.multiplicand]) groups[cell.multiplicand] = []
        groups[cell.multiplicand].push(cell)
      })
      return Object.values(groups)
    })

    watch([max, triangular], load)
    load()

    return { max, triangular, grouped }
  }
}).mount('#app')
</script>

CSS 樣式建議(讓表格好看)

<style>
.multiplication-table {
    border-collapse: collapse;
    font-family: 'Courier New', monospace;
    font-size: 0.9rem;
    margin: 1rem auto;
}
.multiplication-table td {
    border: 1px solid #ddd;
    padding: 0.4rem 0.6rem;
    text-align: right;
    min-width: 4.5ch;
}
.multiplication-table tr:first-child td { background: #f8f9fa; font-weight: bold; }
.multiplication-table td:first-child { background: #f8f9fa; font-weight: bold; }
.multiplication-table td:nth-child(odd) { background: #fafafa; }

教學應用延伸

  1. 遞迴版本: 用遞迴函數替代迴圈,理解遞迴終止條件
  2. 格式化輸出: 練習 printf、sprintf、str_pad、number_format
  3. 效能比較: 字串拼接 vs 陣列 implode vs 輸出緩衝 ob_start
  4. 單元測試: 驗證乘積正確性、行數、欄位數、邊界值
  5. 國際化: 支援阿拉伯數字、羅馬數字、中文大寫數字輸出

總結

九九乘法表雖小,卻能練習迴圈控制、資料結構、輸出格式化、函數封裝、前後端分離等完整開發技能。建議初學者從版本一入手理解邏輯,進階至版本三學習封裝與參數化,最終嘗試版本四體驗 API 設計與前端框架整合。程式設計的核心不在語法,而在於如何將問題分解、抽象、組合、驗證——這正是九九乘法表這類「玩具程式」的真正價值。

copyright © 萬盛學電腦網 all rights reserved