首页 > 解决方案 > 基于颜色的PHP颜色编码

问题描述

我正在尝试学习 PHP,同时为冠状病毒爆发创建本地仪表板,在我看来,我一直做得很好,但真的坚持下去。

我正在尝试从我的数据库中提取数据并根据结果对其进行颜色编码。

通过使用以下代码,我能够以我想要的格式很好地显示它,但对如何以颜色显示它感到非常困惑

我正在使用的数字是从绿色的 0.00000000 到红色的 0.00104348。

任何帮助将不胜感激

$sql = "SELECT FORMAT(conf / pop, 8) as pop_inf from cases ORDER BY id DESC LIMIT 1;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
    while ($row = mysqli_fetch_assoc($result)){
        echo $row['pop_inf'] . "%";
    }
}

标签: phpcsssql

解决方案


如果您的意图是根据其范围为每个值创建红色渐变比例,那么最简单的解决方案是将范围映射到颜色代码。

例如

const MAX = 0.00104348;
// this gives you the percentage of red (from 0.00 to 1.0) based on the MAX value
$color = $row['pop_inf'] / MAX; 
// now we translate that to an 8-bit hexadecimal value
$color = (int) (256 * $color) - 1;
// pad it to a 2 digit hex string
$color = sprintf("%02x", base_convert($color, 10, 16));
// Now you can print a full hex value color as 0x000000 - 0xff0000
$color = "$color0000";

推荐阅读