简体   繁体   中英

PHP alternate row colour based on content

I have searched on here and Google but I have been un able to find a solution that I can integrate.

I have rows of data populated from a MySQL database, what I would like to do is alternate the row colour when a certain column changes. For example:

Sponsor    Name
John       Terry
John       Bob
John       Paul
Grant      Peter
Perry      Toby
Perry      Gerald

So, all of John's rows would have a background colour of row1, Grant row2, then Perry would be row1 again.

I contemplated doing a simple switch and alternating them that way, but with 20 (and growing) different possibilities for Sponsor, I wanted to know if there was a simpler way.

Is there any easier way out there, or is doing it via a switch statement going to be the way to go?

Cheers

Here is a general way to accomplish this. If you understand the concept, you should be able to adapt it to fit your specific needs. Basically, keep track of the previous item as you iterate over your query results. If the current item is different, then change the color.

$sponsors = ['John', 'John', 'Grant', 'Perry', 'Perry'];

$color = null;
$previous_sponsor = null;

foreach ($sponsors as $sponsor) {
    if ($sponsor != $previous_sponsor) {
        $color = $color == 'red' ? 'green' : 'red';
        $previous_sponsor = $sponsor;
    }
    echo "$sponsor $color<br>";
}

Here is a general way to do stuff like that:

$dataArray = array(
    array('sponsor' => 'John',  'name' => 'Terry'),
    array('sponsor' => 'John',  'name' => 'Bob'),
    array('sponsor' => 'Grant', 'name' => 'Peter'),
    array('sponsor' => 'Grant', 'name' => 'Peter'),
    array('sponsor' => 'John',  'name' => 'Bob'),
    array('sponsor' => 'John',  'name' => 'Bob'),
    array('sponsor' => 'Grant', 'name' => 'Peter'),
    array('sponsor' => 'Grant', 'name' => 'Peter'),
    array('sponsor' => 'John',  'name' => 'Bob'),
);

$colors = array('red', 'green', 'blue');
$currentColorIndex = 0;

echo '<table>';
foreach ($dataArray as $key => $data) {
    if ((key($dataArray) > 0) && ($data['sponsor'] !== $dataArray[key($dataArray) - 1]['sponsor'])) {
        $currentColorIndex = ($currentColorIndex + 1) % count($colors);
    }
    echo '<tr style="background-color: ' . $colors[$currentColorIndex] . '">' .
             '<td>' . $data['sponsor'] . '</td>' .
             '<td>' . $data['name'] . '</td>' .
         '</tr>';
}
echo '</table>';

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