首页 > 解决方案 > 在特定的 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 行”的值?

非常感谢您的帮助!

标签: phploopshtml-table

解决方案


您可以尝试类似的方法 - 请注意这是未经测试的代码:

$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, "&nbsp;" );
$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, "&nbsp;" );
        $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>";    

推荐阅读