简体   繁体   中英

Apply CSS class to dynamic table data

I have a MySQL database with 35 different columns labeled 1-35. The data is displayed in a dynamic table. I am looking for the PHP code that would allow me to apply a CSS class to specific cells based on what is returned inside them.

EXAMPLE: Column 1 can return either TRUE or FALSE value. If a TRUE value is returned, I want to give that cell a different background color, or highlight it.

I have the CSS class as:

.highlight {
background-color: #FC0;
}

After the CSS class has then been applied to the specific cells from columns 1-35, I would like the PHP code that can total the number of highlighted cells in the column labeled TOTAL.

Can't seem to find the PHP code to tie all this together. If someone could advise, I'd be very grateful.

<td class="<?php if ($row['item'] == TRUE)
{
    echo 'highlight';
    $highlights++;
}
else
{
    echo 'no_highlight';
}
?>"><?php echo $row['item'];?></td>

and then...

<td id="totalHighlights"><?php echo $highlights;?></td>

EDIT: Sample code...

<?php

//We've queried the database and passed the results into $result via mysql_fetch_assoc().

while ($row = $result)
{
    //Clear highlights and values arrays for each row.
    $highlights = array();
    $values = array();
    foreach($row as $entry)
    {
        if ($entry == TRUE)
        {
            //Put a truthy value into highlights array.
            array_push($highlights, 1);
        }
        else
        {
            //Put a falsey value into highlights array.
            array_push($highlights, 0);
        }

        //Push actual field value to values array.
        array_push($values, $entry);
    }
    echo '<tr class="row">';

    //Create cell with total highlights per row using the array_sum() of highlights.
    echo '<td class="row_total_highlights">'.array_sum($highlights).'</td>';

    //Create each value cell and populate them with each field value from values array.
    $i = 0;
    foreach ($values as $value)
    {
        echo '<td class="entry ';
        echo ($highlights[$i] == 1 ? 'trueClass' : 'falseClass');
        echo '">'.$value.'</td>';
        $i++;
    }
    echo '</tr>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM