我有一个表将显示数据库中的数据。这些数据计数是dynamic
。我想每排显示4个。然而,最后一行的问题。我想如果最后一行有1个TD,函数会给这个TD一个4的colspan
,这样我就可以在在中间显示数据。
NUMBER OF DATA IS 5
###############################################
# TABLE HEADER(colspan=4) #
###############################################
|| TD1 || TD2 || TD3 || TD4 ||
|| TD5 ||
I NEED THIS
###############################################
# TABLE HEADER(colspan=4) #
###############################################
|| TD1 || TD2 || TD3 || TD4 ||
|| TD5 ||
and if there are 6 TDS to show it like this.
###############################################
# TABLE HEADER(colspan=4) #
###############################################
|| TD1 || TD2 || TD3 || TD4 ||
|| TD5 || TD6 ||
我的PHP代码+HTML
<table>
<tr>
<th colspan="4">TABLE HEADER</th>
</tr>
<tr>
<? $counter = 0;
foreach($data as $d)
{
if($counter % 4 == 0)
{
echo '</tr><tr>';
}
echo $d['name'];
$counter++
}
?>
</tr>
</table>
提前谢谢。
以下是一些入门知识。它可能不是最优雅的,但它会的。
<tr>
<? $counter = 0;
$lastrow = floor($count($data)/4)*4;
$numinlastrow = $count($data)%4;
foreach($data as $d)
{
if($counter % 4 == 0)
{
echo '</tr><tr>';
}
$colspan = 1;
if ($counter >= $lastrow) {
if ($numinlastrow == 1) $colspan = 4;
if ($numinlastrow == 2) $colspan = 2;
if ($numinlastrow == 3) ; // ??
}
echo "<td colspan='".$colspan."'>";
//... contents of table cell here
echo "</td>";
$counter++
}
?>
</tr>
如果有3个表单元格,那么使用上面的方法是不可能的,因为colspan
只能跨越整个表列(没有分数)。
因此,相反,将一个表放在横跨整行的表单元格中。。。
<tr>
<? $counter = 0;
$lastrow = floor($count($data)/4)*4;
$numinlastrow = $count($data)%4;
foreach($data as $d)
{
if($counter % 4 == 0)
{
if ($counter >= $lastrow) {
echo '</tr><tr><td colspan="4"><table><tr>';
}
else echo '</tr><tr>';
}
echo "<td>";
//... contents of table cell here
echo "</td>";
$counter++
}
if ($numinlastrow != 0) echo '</tr></table></td>'
?>
</tr>
我会用以下方式(大致)来做这件事——尽管这看起来有点傻,但我目前想不出更好的方法:
$num_of_rows = mysql_num_rows($result);
for ($i = 0; $i < ($num_of_rows / 4); $i++)
{
for ($j = 0; $j < 4; $j++)
{
$row = mysql_fetch_assoc($result);
echo $row['name'];
}
echo '</tr><tr>';
}
if (mysql_num_rows($result) == 3)
{
mysql_fetch_assoc($result);
echo '<td colspan="2">'.$row['name'].'</td>';
mysql_fetch_assoc($result);
echo '<td>'.$row['name'].'</td>';
mysql_fetch_assoc($result);
echo '<td>'.$row['name'].'</td>';
}
else
{
while($row = mysql_fetch_assoc($result))
{
echo '<td colspan="'.(4 / mysql_num_rows($result)).'">'.$row['name'].'</td>';
}
}