[英]How to convert multidimensional PHP array to html table
I'm trying to make a HTML table out of a multidimensional array variable $array2
which is a query(from a mysql database PHP query and Not a self-made query) and is as follows; 我正在尝试用多维数组变量
$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
)
)
I want to make the table appear like this 我想让表格看起来像这样
|ID |FIRST NAME| LAST NAME | CITY | PHONE |
________________________________________________________
|M2TYEE | Jean | Harvey | London | 0314686334 |
--------------------------------------------------
|E26YBE | Tom | Cruise | New York | 0635625735 |
They array may increase to upto say 1000 values so using a while/for loop would be necessary. 它们可能会增加到1000个值,因此使用while / for循环是必要的。 Any help will be highly appreciated
任何帮助将受到高度赞赏
You can use array_merge
and foreach
for the desired output 您可以使用
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;
because your internal array are fixed with size ( all have 4 field) , you can use single loop as below: 因为你的内部数组是用大小固定的(都有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>";
Another approach: 另一种方法:
$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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.