根据字段值替换行颜色


Alternate row color based on field value

考虑以下代码:

<?php foreach($payment_type->revisionHistory as $history): ?>
    <tr>
        <td><?= $history->userResponsible()->alias ?></td>
        <td><?= $history->fieldName() ?></td>
        <td><?= $history->oldValue() ?></td>
        <td><?= $history->newValue() ?></td>
        <td><?= $history->created_at ?></td>
    </tr>                        
<?php endforeach; ?>

我希望仅当created_at字段值与上一次迭代不同时才能更改行颜色,并在值相同时保持相同的行颜色。

我试过一些方法,但结果真的很糟糕。

您应该将其与css混合,但这很容易:

<?php 
$lastCreatedAt = ''; // for storing value of the previous date, start with empty
$classNameEven = TRUE; // begin with "even" class
foreach($payment_type->revisionHistory as $history):
   $switchClass = ($lastCreatedAt != $history->created_at);
   if ($switchClass) {
      $classNameEven = !$classNameEven;
   }
?>
    <tr class="<?php echo ($classNameEven ? 'even' : 'odd'); ?>">
        <td><?= $history->userResponsible()->alias ?></td>
        <td><?= $history->fieldName() ?></td>
        <td><?= $history->oldValue() ?></td>
        <td><?= $history->newValue() ?></td>
        <td><?= $history->created_at ?></td>
    </tr>
    <?php  //remember the last date for next iteration
    $lastCreatedAt = $history->created_at; 
    ?>
<?php endforeach; ?>

然后你需要在这个表中添加一些CSS,比如:

<style>
table tr.even td {
   background-color: #FFF;
}
table tr.odd td {
   background-color: #999; //odd rows have darker background
}
</style>