如何显示以月份作为标题和缺失数据的 html 表


How to display html table with months as headers and missing data

我需要制作一个表格来显示不同网站的评估分数,但并非每个网站都有每个月的数据。如何将数据放入正确的月份列,然后在没有数据的地方显示空白单元格?

这是一个示例数组:

Array
(
[Site 1] => Array
    (
        [1] => 89
        [3] => 84
        [4] => 96
        [6] => 91
        [8] => 90
        [12] => 99
    )
[Site 2] => Array
    (
        [1] => 90
        [3] => 93
        [4] => 88
    )
[Site 3] => Array
    (
        [1] => 92
        [3] => 92
        [4] => 89
        [6] => 94
        [8] => 86
    )
[Site 4] => Array
    (
        [1] => 93
        [2] => 88
        [3] => 92
        [4] => 89
        [5] => 93
        [6] => 94
        [8] => 90
        [12] => 91
    )
)

这就是我对 php 的了解。我知道 for 循环有问题,但我不知道该怎么办。任何帮助,不胜感激。

echo "<table width='100%' border='1'>";
echo "<tr><th>Sites</th><th>Jan</th><th>Feb</th><th>Mar</th><th>Apr</th><th>May</th><th>Jun</th><th>Jul</th><th>Aug</th><th>Sep</th><th>Oct</th><th>Nov</th><th>Dec</th>";  
foreach($report as $site=>$array)
{
    echo "<tr><td>$site</td>";
    foreach($array as $month=>$score)
    {
        for($i=1;$i<=12;$i++)
        {
            if($month==$i)
            {
                echo "<td>$score</td>";
            }
            else
            {
                echo "<td>&nbsp;</td>";
            }
        }           
    }       
    echo "</tr>";
}   
echo "</table>";
您需要

检查每个$i是否存在一个月。您正在做的是检查每个$i是否等于每个月,当然,这几乎总是错误的,并且会产生大量的空单元格。只需查看您总共生成了多少个单元格(每行):赢得站点的月数乘以 12。

这是一个正确的方法:

echo "<table width='100%' border='1'>";
echo "<tr><th>Sites</th><th>Jan</th><th>Feb</th><th>Mar</th><th>Apr</th><th>May</th><th>Jun</th><th>Jul</th><th>Aug</th><th>Sep</th><th>Oct</th><th>Nov</th><th>Dec</th>";
foreach($report as $site=>$array)
{
    echo "<tr><td>$site</td>";
    for($i=1;$i<=12;$i++)
    {
        if (isset($array[$i]))
        {
            echo "<td>".$array[$i]."</td>";
        }
        else
        {
            echo "<td>&nbsp;</td>";
        }
    }
    echo "</tr>";
}
echo "</table>";

或者,更短,

echo "<table width='100%' border='1'>";
echo "<tr><th>Sites</th><th>Jan</th><th>Feb</th><th>Mar</th><th>Apr</th><th>May</th><th>Jun</th><th>Jul</th><th>Aug</th><th>Sep</th><th>Oct</th><th>Nov</th><th>Dec</th>";
foreach($report as $site=>$array)
{
    echo "<tr><td>$site</td>";
    for($i=1;$i<=12;$i++)
    {
        echo "<td>".(isset($array[$i]) ? $array[$i] : '&nbsp;')."</td>";
    }
    echo "</tr>";
}
echo "</table>";

在 for 循环中验证密钥是否存在于 issset 或 array_key_exists

foreach($array as $score){
    for($i=1;$i<=12;$i++){
        if(array_key_exists($i,$score)){
            echo '<td>'.$scode[$i].'<td>';
        }else{
            echo "<td>&nbsp;</td>";
        }
    }
}