paperjack paperjack - 1 month ago 9
PHP Question

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

I need to make a table displaying evaluation scores for different sites but not every site will have data for each month. How can I get the data into the right month column and then display blank cells where there is no data?

This is a sample array:

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
)

)


And this is as far as I got with the php. I know there is problem with the for loop but I can't figure what to do. Any help is appreciated.

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>";

Answer

You need to check if a month exists for each $i. What you're doing is checking if each $i is equal to each month, which is, of course, almost always false and produces huge number of empty cells. Just see how many cells in total you produce (per row): number of months for won site multiplied by 12.

Here is a proper way to do it:

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>";

or, shorter,

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>";
Comments