在PHP中生成具有重复标题行的表

时间:2018-05-01 15:58:35

标签: php html-table

我需要在PHP中生成this table

所以这是我的尝试:

$days = 7; 
$maxid = 7;
$startid = 1;

$html = "<table id='table1'>\n";
for ($i = 1;$i<=ceil($maxid/$days);$i++) {

    $html .= "<tr>\n";
    for ($j=1;$j<=$days;$j++)
        if ($startid <= $maxid)
            $html .= "  <td class='mark'>DAY ".$startid++."</td>\n";
        else 
            $html .= "  <td> </td>\n";

    $html .= "</tr>\n<tr>\n";
    for ($j=1;$j<=$days;$j++)
        $html .= "<td>Content</td>\n";

    $html .= "</tr>\n";
}

$html .= "</table>\n";

问题是我不知道如何插入MO TU WE TH FR SA SU并且标题不会重复每两行。

1 个答案:

答案 0 :(得分:0)

您可以将MO,TU等分配给数组并迭代它以提取重复标题的值。从那里,您可以使用Modulo Operator来确定何时回显了两行并重复您的标题:

$days = 7; 
$maxid = 7;
$startid = 1;

$dayLabels = array('MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU');

$html = "<table id='table1'>\n";
for ($i = 1;$i<=ceil($maxid/$days);$i++) {

    $html .= "<tr>\n";
    if($i % 2 == 1) {
        foreach($dayLabels as $label) {
            $html .= " <th>$label</th>";
        }
        $html .= "</tr><tr>";
    }
    for ($j=1;$j<=$days;$j++)
        if ($startid <= $maxid)
            $html .= "  <td class='mark'>DAY ".$startid++."</td>\n";
        else 
            $html .= "  <td> </td>\n";

    $html .= "</tr>\n<tr>\n";
    for ($j=1;$j<=$days;$j++)
        $html .= "<td>Content</td>\n";

    $html .= "</tr>\n";
}

$html .= "</table>\n";