我需要制作一个显示不同网站评估分数的表格,但不是每个网站都会有每个月的数据。如何将数据输入正确的月份列,然后显示没有数据的空白单元格?
这是一个示例数组:
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> </td>";
}
}
}
echo "</tr>";
}
echo "</table>";
答案 0 :(得分:1)
您需要检查每个$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> </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] : ' ')."</td>";
}
echo "</tr>";
}
echo "</table>";
答案 1 :(得分:0)
在for循环中验证密钥是否存在于isset或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> </td>";
}
}
}