用数据库结果填充html表

时间:2015-02-13 22:06:47

标签: php jquery html

我必须构建如下所示的html表: enter image description here

但是我从数据库中得到的字段和头名。第一个查询 - 返回字段描述,第二个查询重新返回字段值。 我花了很多时间试图达到这个目的。所以我做了什么:

<table>
<tbody>
<?php
foreach ($comments as $comment) {   // $comments is array of strings                      
?>
     <td><b><?= $comment ?></b></td>
<?php}?>
</tbody>  
<?php
   foreach ($field_names as $fn) { // $field_names is array_keys($result)
   ?><tr><?php
     foreach ($result as $r) {  // $result - values of fields                          
     ?>
     <td><?= $r[$fn] ?></td>
     <?php
     }?>
</tr>
<?php
}
?></table>

但是通过这种方式,我可以调换我的内容。任何帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

好的,既然你没有提供变量信息,我将假设以下内容,如果是这样,这段代码应该适合你:

<?php
    $comments = ["comm1", "comm2", "comm3"]; // $comments is array of strings

    $field_names = array(
        0 => "fv1",
        1 => "fv2",
        2 => "fv3"
    ); // $field_names is array_keys($result)

    $result = ["value1", "val2", "val3"]// $result - values of fields
    ?>
    <table>
        <thead>
            <tr>
                <?php foreach ($comments as $comment) { ?>
                    <th><b><?= $comment ?></b></th>
                <?php } ?>
            </tr>
        </thead>
        <tbody>
            <tr>
                <?php foreach ($field_names as $k => $v) { ?>
                    <td><?= $result[$k] ?></td>
                <?php } ?>
            </tr>
        </tbody>
    </table>

更新:

<style>
    .tbl_hdr{
        font-weight: bold;
    }
</style>
<?php
$comments = ["comm1", "comm2", "comm3"]; // $comments is array of strings
$field_names = array(
   0 => "fv1",
   1 => "fv2",
   2 => "fv3"
); // $field_names is array_keys($result)

$result = ["value1", "val2", "val3"]// $result - values of fields
?>
<table>
    <?php foreach ($field_names as $k => $v) { ?>
        <tr>
            <td class="tbl_hdr"><?= $comments[$k] ?></td>
            <td><?= $result[$k] ?></td>
        </tr>
    <?php } ?>
</table>