我目前正在制作一个页面,使用php将数据从mysql数据库输出到页面上,如下所示:

echo "<tr>";
echo "<td><span style='font-weight:bold; font-size:18px'>Physical</span></td><td><span style='font-size:18px;'>" . $row['attributePhy'] . "</span></td>";
echo "<tr>";
echo "<td><span style='font-weight:bold; font-size:14px;'>Jumping </span></td><td><span style='font-size:14px;'>" . $row['jumping'] . "</span></td>";
echo "<tr>";
echo "<td><span style='font-weight:bold; font-size:14px;'>Stamina </span></td><td><span style='font-size:14px;'>" . $row['stamina'] . "</span></span></td>";
echo "<tr>";
echo "<td><span style='font-weight:bold; font-size:14px;'>Strength </span></td><td><span style='font-size:14px;'>" . $row['strength'] . "</span></td>";
echo "<tr>";
echo "<td><span style='font-weight:bold; font-size:14px;'>Aggression </span></td><td><span style='font-size:14px;'>" . $row['aggression'] . "</span></td>";


但是我想要它,以便数字结果的颜色根据数字的高低而变化,例如红色为60及以下,浅绿色为61至80,深绿色为81+

有什么办法可以对整个表执行此操作吗?上面的代码只是一个很小的示例,每个代码的if语句将花费很长时间。

编辑:

我只想更改结果颜色,例如

<span style='font-size:14px;'>" . $row['aggression'] . "</span>
<span style='font-size:14px;'>" . $row['strength'] . "</span>


这将作为数据库的数字返回,该数字是需要更改颜色的位。
等等

最佳答案

您只需要一个条件语句:
在此示例中,我将使用三元运算符:

function getColor($value){
    return ($value <= 60 ?
                'color: red;'
                :
                ($value > 60 && $value < 81  ?
                    'color: lightgreen;'
                    :
                    ($value >= 81 ?
                        'color: darkgreen'
                        :
                        ''
                    )
                )
            );
}


您可以按以下方式使用它:

echo "<td><span style='font-size:18px;". getColor($row['attributePhy'])."'>" . $row['attributePhy'] . "</span></td>";

07-28 02:24
查看更多