【问题标题】:Empty Cell in HTML Table when filled with PHP Array填充 PHP 数组时 HTML 表中的空单元格
【发布时间】:2020-07-21 15:49:11
【问题描述】:

我刚刚用一个 php 数组填充了一个 html 表,但现在我看到我有一些空单元格。建表的代码是:

echo "<table id='data' style='border: 1px solid black'><tbody>";
echo "<th>Country </th>";
echo "<th>Counter</th>";
foreach($analysis_data as $row){
    echo "<tr>";
    foreach(['country','counter'] as $attribute){
        echo "<td>".$row[$attribute]."<td>";
    }
    echo '</tr>';
}
echo '</tbody></table>';

表格目前的样子有截图

如果我使用var_dump($analysis data),它看起来像

array(9) { [0]=> array(2) { ["country"]=> string(30) "Germany " ["counter"]=> int(34) } [1]=> array(2) { ["country"]=> string(30) "Vorarlberg " ["counter"]=> int(2) } [2]=> array(2) { ["country"]=> string(30) "Oberoesterreich " ["counter"]=> int(9) } [3]=> array(2) { ["country"]=> string(30) "Wien " ["counter"]=> int(5) } [4]=> array(2) { ["country"]=> string(30) "Switzerland " ["counter"]=> int(3) } [5]=> array(2) { ["country"]=> string(30) "Salzburg " ["counter"]=> int(6) } [6]=> array(2) { ["country"]=> string(30) "Niederoesterreich " ["counter"]=> int(1) } [7]=> array(2) { ["country"]=> string(30) "Czech Republic " ["counter"]=> int(3) } [8]=> array(2) { ["country"]=> string(30) "Steiermark " ["counter"]=> int(1) } }

这个空单元格来自哪里以及如何删除它们?

【问题讨论】:

    标签: php html html-table


    【解决方案1】:

    修复您的 html 标记:

    // Create `thead` for header and open `tr` for first row
    echo "<table id='data' style='border: 1px solid black'><thead><tr>";
    echo "<th>Country </th>";
    echo "<th>Counter</th>";
    
    // Close `tr` and `thead`, open `tbody`
    echo "</tr></thead><tbody>";
    
    foreach($analysis_data as $row){
        echo "<tr>";
        foreach(['country','counter'] as $attribute){
            echo "<td>".$row[$attribute]."</td>";    // close `td` here
        }
        echo '</tr>';
    }
    echo '</tbody></table>';
    

    【讨论】:

    • echo "&lt;td&gt;".$row[$attribute]."&lt;td&gt;"; 小心关闭标签,它会产生不必要的单元格
    猜你喜欢
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 2016-03-03
    相关资源
    最近更新 更多