Possible Duplicate:
php: how to add odd/even loop in array
I am generating a table in php with the below code.
<?PHP
while ($row = $mydata->fetch())
{
$tests[] = array(
'a' => $row['a'],
'b' => $row['b']
)
;
}
?>
Then the output code
<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>
which outputs
<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 is the below custom function.
<?php
function html($text)
{
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
function htmlout($text)
{
echo html($text);
}
?>
This is all working well but I can’t work out two things here.
- I want my rows to generate
<tr class="odd">and<tr class="even">on alternate rows - I want the first
<td></td>within the<tr>to count show the row number of the data eg<td>1</td>in the first<tr class=""> <td>2</td>in the second etc.
I have looked at numerous examples such as this
$count = 1;
while ($count <= 10)
{
echo "$count ";
++$count;
}
But can’t work out how to implent it into my example or maybe I should use another method. I understand I can do the table rows in jQuery and in some browsers with css3 but would prefer a php solution in this case.
You can use something like this:
This leverages the fact that the array keeps a numerical index
$i. So, the row number is really$i + 1, which we put into the first column. Then, we determine if the current row is even or odd based on whether or not$iis divisible by 2. If$iis divisible by 2, it’s an even row, otherwise it’s an odd row. We save the class string in$class, and put it in the<tr>tag.