如何将多维PHP数组转换为html表
Posted
技术标签:
【中文标题】如何将多维PHP数组转换为html表【英文标题】:How to convert multidimensional PHP array to html table 【发布时间】:2019-09-22 17:32:31 【问题描述】:我正在尝试从多维数组变量$array2
中创建一个 html 表,它是一个查询(来自 mysql 数据库 php 查询而不是自制查询),如下所示;
Array
(
[0] => Array
(
[0] => M2TYEE
[1] => Jean
[2] => Harvey
[3] => London
[4] => 0314686334
)
[1] => Array
(
[0] => E26YBE
[1] => Tom
[2] => Cruise
[3] => New York
[4] => 0635625735
)
)
我想让表格看起来像这样
|ID |FIRST NAME| LAST NAME | CITY | PHONE |
________________________________________________________
|M2TYEE | Jean | Harvey | London | 0314686334 |
--------------------------------------------------
|E26YBE | Tom | Cruise | New York | 0635625735 |
它们的数组可能会增加到最多 1000 个值,因此需要使用 while/for 循环。 任何帮助将不胜感激
【问题讨论】:
【参考方案1】:您可以使用array_merge
和foreach
获得所需的输出
$arr = array_merge([ 0 => ['ID','FIRST NAME','LAST NAME','CITY','PHONE']],$arr);
$html = '<table border="1">';
foreach($arr as $row)
$html .= '<tr>';
foreach($row as $column)
$html .= '<td>'.$column.'</td>';
$html .= '</tr>';
$html .= '</table>';
echo $html;
【讨论】:
效果惊人的完美,但将第一行改为$arr = array_merge([ 0 => ['ID','FIRST NAME','LAST NAME','CITY','PHONE']],$array2);
【参考方案2】:
因为你的内部数组的大小是固定的(都有 4 个字段),你可以使用如下的单循环:
echo "<table>";
foreach($array2 as $index)
echo "<tr>";
echo "<td>".$index[0]."</td><td>".$index[1]."</td><td>".$index[2]."</td><td>".$index[3]."</td><td>".$index[4]."</td>";
echo "</tr>";
echo "</table>";
另一种方法:
$result.="<table>";
foreach($array2 as $index)
$result.="<tr>";
$result.="<td>".$index[0]."</td><td>".$index[1]."</td><td>".$index[2]."</td><td>".$index[3]."</td><td>".$index[4]."</td>";
$result.="</tr>";
$result.="</table>";
echo $resul;
【讨论】:
不太好用,但很有帮助。谢谢 @KalisploitTutorials,每个字段只能添加<tr><th>Your Header title</th></tr>
。以上是关于如何将多维PHP数组转换为html表的主要内容,如果未能解决你的问题,请参考以下文章