php - 在特定的 HTML 表格单元格中显示来自 DB 的值
问题描述
我正在尝试从特定模式的数据库值中获取表视图。它应该如下所示: 平面图
在数据库中,我添加了行/列值以将“单元格名称”分配给特定单元格:
使用此代码:
$maxrow = getResult($pdo, "SELECT MAX(row) AS maxrow FROM stalls")["maxrow"];
$maxcol = getResult($pdo, "SELECT MAX(col) AS maxcol FROM stalls")["maxcol"];
$data = $pdo->query("SELECT row, col, number FROM stalls ORDER BY row ASC, col ASC")->fetchAll();
echo'<table style="width:100%;">';
foreach ($data as $entry)
{
if($entry['row'] > 0)
{
for($r=0;$r<=$maxrow;$r++)
{
if($r == $entry['row'])
{
echo '<tr style="border: 1px solid black;">';
for($c=1;$c<=$maxcol;$c++)
{
if($c == $entry['col'])
{
echo '<td style="border: 1px solid black;">row: '. $r . ' - col: ' . $c . ' - value: ' . $entry['number'] .'</td>';
}
else
{
echo '<td style="border: 1px solid black;"></td>';
}
}
echo '</tr>';
}
}
}
}
echo '</table>';
我只能得到这样的看法:
在没有“移位”的情况下,如何在第 1 行中显示“第 1 行”的值?
非常感谢您的帮助!
解决方案
您可以尝试类似的方法 - 请注意这是未经测试的代码:
$maxrow = getResult($pdo, "SELECT MAX(row) AS maxrow FROM stalls")["maxrow"];
$maxcol = getResult($pdo, "SELECT MAX(col) AS maxcol FROM stalls")["maxcol"];
$oldRow = 0; // init row counter
$arr = array_fill( 0, $maxcol, " " );
$tmp = "";
echo'<table style="width:100%;">';
foreach ($data as $entry) {
// get the data
$row = $entry['row'];
$col = $entry['col'];
$nbr = $entry['number'];
// is the row number different and not the first entry
if( $oldRow != $entry['row'] && $oldRow != 0 ) {
//--- convert to html type string
$tmp = implode( "</td><td>", $arr );
//--- show html
echo'<tr><td>".$tmp."</td></tr>";
//--- reset temp values
$arr = array_fill( 0, $maxcol, " " );
$oldRow = $entry['row']; // set new row number
}
$arr[$row][$col] = $nbr;
}
//--- convert to html type string for last entry processed
$tmp = implode( "</td><td>", $arr );
//--- show html
echo'<tr><td>".$tmp."</td></tr>";
echo "</table>";
推荐阅读
- mysql - 如果我要在单独的 docker 容器中使用 mysql,我是否需要 Spring Initializr 中的 mysql 依赖项?
- raspberry-pi - 为什么我的 RPi UART0 (ttyAMA0) 在禁用蓝牙时会死机?
- android - 设备重新启动(或类似状态)Android 时本地通知不显示
- mongodb - 在 phoenix/elixir 中使用 mongodb 驱动程序进行深度查询
- java - 为什么我得到 UNAUTHORIZED_DOMAIN:Domain 没有被项目列入白名单?
- angular - 部署和托管 Angular 前端和 Go 后端
- batch-file - 从批处理脚本进行 NuGet 还原
- docker - Docker Splunk 日志记录驱动程序是否支持 indexer ack
- browser - 在 Vaadin 14 应用程序的服务器端通过 Java 获取用户 Web 浏览器的 IP 地址
- flutter - Dart 或 Flutter:我如何获得处理器内核的数量?