简体   繁体   English

PHP 基于内容的交替行颜色

[英]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.我有从 MySQL 数据库填充的数据行,我想做的是在特定列更改时交替行颜色。 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.所以,John 的所有行的背景颜色都是 row1,Grant row2,然后 Perry 又是 row1。

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.我打算做一个简单的切换并以这种方式交替它们,但是对于 Sponsor 有 20 种(并且还在不断增加)不同的可能性,我想知道是否有更简单的方法。

Is there any easier way out there, or is doing it via a switch statement going to be the way to go?有没有更简单的方法,或者是通过 switch 语句来做吗?

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>';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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