首页 > 解决方案 > 如何为视图中的非唯一记录设置相同的颜色

问题描述

我正在尝试创建表行中的相同数据是否在视图中显示为红色。

这是表中的输出

<tbody>
<?php 

$i = 1;
foreach ($data as $item) : 

?>
<tr>
    <td>
    <?php
        $text = $item->serial;

        if ($text == $text) {
            echo '<span class="text-danger">' . $text . '</span>';
        } else {
            echo '<span class="text-success">' . $text . '</span>';
        }
    ?>
    </td>
</tr>

<?php 

endforeach;

?>

</tbody>

标签: phpalgorithmcodeigniter

解决方案


您将需要通过循环和设置serial为键来保持序列号的计数。如果 key 再次出现,增加它。循环显示数据时,如果serialcount 大于1,则进入red,否则为黑色。

片段:

<tbody>
<?php 

$i = 1;

$serial_count = [];

foreach($data as $item):
    $serial_count[$item->serial] = (isset($serial_count[$item->serial]) ? $serial_count[$item->serial] : 0) + 1;
endforeach;

foreach ($data as $item) : 

?>
<tr>
    <td>
    <?php
        $text = $item->serial;

        if ($serial_count[$text] > 1) {
            echo '<span class="text-danger">' . $text . '</span>';
        } else {
            echo '<span class="text-success">' . $text . '</span>';
        }
    ?>
    </td>
</tr>

<?php 

endforeach;

?>

</tbody>

推荐阅读