用rowspan php创建表

时间:2019-03-18 09:27:10

标签: php html html-table

我一直试图找出如何在php中创建下表,然后将其包含在另一页上,我要创建的表是:

What I want to display

我一直在使用以下代码,该代码适用于第一行跨行,但不适用于任何其他行:

<?php
    $tbl1 = sqlsrv_query($connys,"

    select SectorTitle,DataTitle,sum(Aug18)[Aug18],sum(Sep18)[Sep18],sum(Oct18)[Oct18],sum(Nov18)[Nov18],sum(Dec18)[Dec18],sum(Jan19)[Jan19],sum(Feb19)[Feb19],sum(Mar19)[Mar19],sum(Apr19)[Apr19],sum(May19)[May19],sum(Jun19)[Jun19],sum(Jul19)[Jul19]
    from tblsomename

    ");
    if($tbl1 === false){
        die( print_r( sqlsrv_errors(), true));
    }
    while( $row = sqlsrv_fetch_array($tbl1, SQLSRV_FETCH_BOTH)){
    echo "<tr>";
    echo "<td rowspan='3'>".$row['SectorTitle']++."</td>";

        while( $row2 = sqlsrv_fetch_array($tbl1, SQLSRV_FETCH_BOTH)){
    $DataTitle=$row2['DataTitle'];
    $Aug=$row2['Aug18'];
    $Sep=$row2['Sep18'];
    $Oct=$row2['Oct18'];
    $Nov=$row2['Nov18'];
    $Dec=$row2['Dec18'];
    $Jan=$row2['Jan19'];
    $Feb=$row2['Feb19'];
    $Mar=$row2['Mar19'];
    $Apr=$row2['Apr19'];
    $May=$row2['May19'];
    $Jun=$row2['Jun19'];
    $Jul=$row2['Jul19'];
    echo "<td>$DataTitle</td><td>$Aug</td><td>$Sep</td><td>$Oct</td><td>$Nov</td><td>$Dec</td><td>$Jan</td><td>$Feb</td><td>$Mar</td><td>$Apr</td><td>$May</td><td>$Jun</td><td>$Jul</td></tr>";
    }

    }

    ?>

该查询不是实际查询,但由于确实提取了相同的标头,因此为您提供了一个思路。然后将其包含在另一个php文件中,该文件将其插入标签等之间。

我的代码当前产生的是:

enter image description here

虽然我似乎无法让它遍历扇区标题位,但这是正确的

1 个答案:

答案 0 :(得分:2)

我认为您可以通过一个while循环与一些附加逻辑来处理跨行:

$SectorTitle = "";

while( $row = sqlsrv_fetch_array($tbl1, SQLSRV_FETCH_BOTH)){
    echo "<tr>";

    // Check if there is a new sectortitle
    if($SectorTitle != $row['SectorTitle']) {
        $SectorTitle = $row['SectorTitle'];
        echo "<td rowspan='3'>$SectorTitle</td>";
    }

    $DataTitle=$row['DataTitle'];
    $Aug=$row['Aug18'];
    $Sep=$row['Sep18'];
    $Oct=$row['Oct18'];
    $Nov=$row['Nov18'];
    $Dec=$row['Dec18'];
    $Jan=$row['Jan19'];
    $Feb=$row['Feb19'];
    $Mar=$row['Mar19'];
    $Apr=$row['Apr19'];
    $May=$row['May19'];
    $Jun=$row['Jun19'];
    $Jul=$row['Jul19'];
    echo "<td>$DataTitle</td><td>$Aug</td><td>$Sep</td><td>$Oct</td><td>$Nov</td><td>$Dec</td><td>$Jan</td><td>$Feb</td><td>$Mar</td><td>$Apr</td><td>$May</td><td>$Jun</td><td>$Jul</td></tr>";
}