更改PHP输出的特定字符的颜色 [英] Change the color of specific characters of a PHP output

查看:629
本文介绍了更改PHP输出的特定字符的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个php查询,它从数据库中获取数据后显示值.显示的值类似于"T","F"或"R". echo命令运行正常.当网页中显示特定值时,我想更改它们的颜色.例如,"T"应为绿色,"F"应为红色,"R"为黄色.我该如何实现?

I have a php query which displays values after fetching data from database. The displayed values are like 'T', 'F' or 'R'. The echo command is working fine. I want to change the color of specific values when they are displayed in web page. For example- 'T' should be in green, 'F' should be in red and 'R' in yellow. How can I acheive that?

谢谢!

以下是我的代码的一部分.我应该在代码的哪里插入样式元素?

Following is a part of my code. Where should I insert the styling elements in the code?

$sql = "select * from <database table> where attribute1 = '$val1' and attribute2 = '$val2'";        
$fetch = $conn->query($sql);

if ($fetch->num_rows > 0) 
    {
         // output data of each row
     while($row = $fetch->fetch_assoc()) 
        {
           echo
              "<tr>
                  <td>".$row["col1"]."</td>
                  <td>".$row["col2"]."</td>
                  <td>".$row["col3"]."</td>
                  <td>".$row["col4"]."</td>
                  <td>".$row["col5"]."</td>
               </tr>";
        }
     echo "</table>";
  } 
else  {
    echo "0 results";
  }

推荐答案

可以使用内联样式来完成,但这是不好的做法.理想情况下,您需要将类应用于输出.

This can be done with in-line styles, however this is bad practice. Optimally, you'll want to apply classes to the output.

例如

<td class="green"></td>
<td class="red"></td>
<td class="yellow"></td>

然后在您的CSS文件中,您将拥有相应的CSS类.

Then within your CSS file, you'll have corresponding CSS classes.

.green{
  color: #0f0;
}

详细了解MDN上的CSS属性color.

根据OP的评论,将我的部分评论添加到答案中.

adding part of my comment to the answer, based on OP's comment.

if($row['col1'] === 'T')
{
  $class = "green";
}

然后在输出<td></td> s时循环:

then when outputting the <td></td>s, loop:

echo "<td class='$class'></td>";

或者:

echo '<td class="' . $class . '"></td>;

这篇关于更改PHP输出的特定字符的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆