php get the number of a given instance in an array
Basically, I'm trying to make a table where the color slightly changes for each row.
I'm going to do this by naming each even row class="even"
and every odd row class="odd"
.
In my loop then, I need to figure out if the instance of the array is odd or even.
I can do almost do this by writing:
if (coun开发者_C百科t($row)%2 == 0) //while $row is an array from a mysql query
{
echo "<tr class='even'>";
if (count($row)%2 == 1)
{
echo "<tr class='odd'>";
}
However writing count($row)
gives me the count for the whole array, not the number of the instance which indicates where it falls in the whole array. Any ideas on how I could get the number of the instance within the array?
Thanks
Don't use PHP for this. Use CSS:
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
Try something like this:
$i = 0;
while ($i < count($row)) {
if (($i % 2) == 0) {
echo "<tr class='even'>";
} else {
echo "<tr class='odd'>";
}
$i++;
}
You could use a counter:
$i = 0
while($row=mysql_fetch_array($yourquery)) {
if ($i % 2 == 0) {
echo "<tr class='even'>";
} else {
echo "<tr class='odd'>";
}
$i++;
}
精彩评论