PHP 中显示表格内容有两种方法:使用 printf 函数格式化输出,步骤包括创建格式化字符串和输出每个行。使用 table 函数生成 HTML 表格,步骤包括创建数据数组和使用 table 函数生成表格。

如何使用 PHP 显示表格内容
在 PHP 中,有两种主要方法可以显示表格内容:
方法 1:使用 printf 函数
printf 函数可用于格式化输出,包括表格。它采用以下语法:
立即学习“PHP免费学习笔记(深入)”;
<code class="php">printf(format, arg1, arg2, ...);</code>
其中:
-
format是一个格式化字符串,指定输出的格式 -
arg1, arg2, ...是要格式化的参数
要使用 printf 函数显示表格内容,可以使用以下步骤:
- 创建一个格式化字符串,包含所需的列和行分隔符。例如:
<code class="php">$format = "| %5s | %10s | %5s |\n";</code>
- 使用
printf函数输出每个行。例如:
<code class="php">printf($format, $col1, $col2, $col3);</code>
方法 2:使用 echo 和 table 函数
PHP 中的 table 函数可以生成一个 HTML 表格,并使用 echo 函数输出。它的语法如下:
<code class="php">echo table($array, $caption, $foot, $border);</code>
其中:
-
array是要显示的数据数组 -
caption是表的标题(可选) -
foot是表的脚注(可选) -
border是表的边框宽度(可选)
要使用 table 函数显示表格内容,可以使用以下步骤:
- 创建一个数组,包含要显示的数据。例如:
<code class="php">$data = [
['Name', 'Age', 'Occupation'],
['John', 30, 'Software Engineer'],
['Jane', 25, 'Doctor']
];</code>- 使用
table函数生成 HTML 表格。例如:
<code class="php">echo table($data);</code>











