<分区>
Possible Duplicate:
php: how to add odd/even loop in array
我正在使用以下代码在 php 中生成一个表。
<?PHP
while ($row = $mydata->fetch())
{
$tests[] = array(
'a' => $row['a'],
'b' => $row['b']
)
;
}
?>
然后是输出代码
<table>
<tbody>
<tr><th>#</th><th>a</th><th>b</th></tr>
<?php foreach ($tests as $test): ?>
<tr class="">
<td></td>
<td><?php htmlout($test['a']); ?></td>
<td><?php htmlout($test['b']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
哪些输出
<table>
<tbody>
<tr><th>#</th><th>a</th><th>b</th></tr>
<tr class="">
<td></td><td>a content</td><td>b content</td>
</tr>
<tr class="">
<td></td><td>a content</td><td>b content</td>
</tr>
</tbody>
</table>
htmlout 是下面的自定义函数。
<?php
function html($text)
{
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
function htmlout($text)
{
echo html($text);
}
?>
这一切都很好,但我无法在这里解决两件事。
- 我希望我的行生成
<tr class="odd">
和<tr class="even">
在隔行 - 我要第一个
<td></td>
在<tr>
内计数显示数据的行号,例如<td>1</td>
在第一个<tr class=""> <td>2</td>
在第二等
我看过很多这样的例子
$count = 1;
while ($count <= 10)
{
echo "$count ";
++$count;
}
但无法弄清楚如何将其实现到我的示例中,或者我应该使用其他方法。我知道我可以在 jQuery 和一些带有 css3 的浏览器中做表格行,但在这种情况下更喜欢 php 解决方案。