将行号和奇偶类添加到php表中
可能重复:将行号和奇偶类添加到php表中,php,mysql,Php,Mysql,可能重复: 我正在用下面的代码用php生成一个表 <?PHP while ($row = $mydata->fetch()) { $tests[] = array( 'a' => $row['a'], 'b' => $row['b'] ) ; } ?> 然后输出代码 <table> <tbody> <tr><th>#</th><th>a</th>
我正在用下面的代码用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>
#ab
哪个输出
<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>
#ab
a内容B内容
a内容B内容
htmlout是下面的自定义函数
<?php
function html($text)
{
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
function htmlout($text)
{
echo html($text);
}
?>
这一切都很好,但我无法解决两件事
和
中的第一个
计数,以显示数据的行号,例如1
在第一个2
在第二个中等
$count = 1;
while ($count <= 10)
{
echo "$count ";
++$count;
}
$count=1;
而($count您可以使用以下内容:
<?php foreach ($tests as $i => $test): ?>
<?php $class = ($i % 2 == 0) ? 'even' : 'odd'; ?>
<tr class="<?php echo $class; ?>">
<td><?php echo $i + 1; ?></td>
<td><?php htmlout($test['a']); ?></td>
<td><?php htmlout($test['b']); ?></td>
</tr>
<?php endforeach; ?>
您只需添加一个循环计数器
<?php $counter = 0 ?>
<table>
<tbody>
<tr><th>#</th><th>a</th><th>b</th></tr>
<?php foreach ($tests as $test): ?>
<tr class="<?= ($counter % 2 == 0) ? 'even' : 'odd' ?>">
<td><?php echo ($counter+1) ?></td>
<td><?php htmlout($test['a']); ?></td>
<td><?php htmlout($test['b']); ?></td>
</tr>
<?php $counter++ ?>
<?php endforeach; ?>
</tbody>
</table>
#ab
解决这个问题最简单的方法可能是从foreach语句切换到for循环。在计数器上使用模运算符应该可以很好地解决这个问题
<table>
<tbody>
<tr><th>#</th><th>a</th><th>b</th></tr>
<?php for( $counter = 0; $counter < count( $tests ); $tests++ ): ?>
<tr class="<? ( $counter % 2 ) ? echo "even" : echo "odd"; ?>">
<td><? echo $counter + 1; ?></td>
<td><?php htmlout($tests[$counter]['a']); ?></td>
<td><?php htmlout($tests[$counter]['b']); ?></td>
</tr>
<?php endfor; ?>
</tbody>
</table>
#ab