【发布时间】:2018-07-22 06:23:41
【问题描述】:
我有一个从 PHP fetchAll() 函数返回的多维数组,如下所示:
$sql="SELECT * FROM users ORDER BY id ASC LIMIT 10";
$stmt = $db->prepare($sql);
$stmt->execute();
$numcolumn = $stmt->columnCount();
$res = $stmt -> fetchAll();
它返回一个这样的数组。
Array
(
[0] => Array
( [0] => 1
[id] => 1
[1] => Firstname one
[firstname] => Firstname one
[2] => Lastname one
[lastname] => Lastname one
)
[1] => Array
(
[0] => 1
[id] => 1
[1] => Firstname one
[firstname] => Firstname one
[2] => Lastname one
[lastname] => Lastname one
)
[2] => Array
(
[0] => 1
[id] => 1
[1] => Firstname one
[firstname] => Firstname one
[2] => Lastname one
[lastname] => Lastname one
)
)
如何在 PHP 中使用循环在这样的 html 表格中打印这些数据?
<table>
<th>
<td>id</td>
<td>firstname</td>
<td>lastname</td>
</th>
<tr>
<td>1</td>
<td>Firstname one</td>
<td>Lastname one</td>
</tr>
</table>
请注意,键和值都来自数据库,而不是静态的。请帮忙。
已编辑:
IT 用于密钥(不工作):
$keys = array_keys($res);
for($i = 0; $i < 1 ; $i++) {
foreach($res[$keys[$i]] as $key => $value) {
$msg.="<th style='background-color:red;'>";
$msg.= $key; //will store column name of the table to msg variable
$msg.="</th>";
}}
$msg.="</tr>";
$i=0;
$count=1; //used to print sl.no
它是为价值观(工作):
foreach($res as $row){
$msg.="<tr><td>".$count."</td>";
for($i=0;$i< $numcolumn;$i++)
{
$var=$row[$i]; //will store all the values of row
$msg.="<td style='white-space: nowrap;word-break: keep-all;'>".$var."</td>";
}
$count=$count+1;
$msg.="</tr>";
}
$msg.="</table>";
echo $msg;
答案:
$res = $stmt -> fetchAll(PDO::FETCH_ASSOC);
$msg="<table><tr><th style='white-space: nowrap;background-color:red;'>Serial No.</th>";
// for keys:
$keys = array_keys($res);
for($i = 0; $i < 1 ; $i++)
{
foreach($res[$keys[$i]] as $keyg => $value)
{
$msg.="<th style='background-color:red;'>";
$msg.= $keyg; //will store column name of the table to msg variable
$msg.="</th>";
}
}
$msg.="</tr>";
$i=0;
$count=1; //used to print sl.no
//for values
foreach($res as $row => $key)
{
$msg.="<tr><td>".$count."</td>";
foreach($key as $C=>$d)
{
$var = $d;
$msg.="<td style='white-space: nowrap;word-break: keep-all;'>".$var."</td>";
}
$count=$count+1;
$msg.="</tr>";
}
$msg.="</table>";
echo $msg; //for printing table in html
【问题讨论】:
-
建议: 在发帖之前,先做一些研究。如果您只需花几分钟时间搜索,就会有 许多 教程/指南/示例。
-
我已经尝试了每个教程,所以在这里发布了一个问题。我被困在从多维数组中打印键。
-
添加您的尝试。
-
编辑了问题。请仔细阅读问题..
标签: php html arrays loops html-table