1

我必须为我的学校调查项目实施条形图,我想我几乎完成了,但没有什么是完美的,这是我的问题。我通过本教程http://www.rgraph.net/docs/integration-with-server-side-scripting.html#mysql实现了这段代码http://www.rgraph.net/docs/bar.html但我有一个问题。我需要根据它的高度绘制图表条,例如等于 3 的值是绿色,小于 1.5 是红色。我使用的代码看起来像这样

print('<script src="../libraries/RGraph.bar.js"></script>' . "\n\n");
print('<canvas id="cvs1" width="600" height="200">[No canvas support]</canvas>' . "\n\n");
print('<script>' . "\n");
print('window.onload = function (){'."\n\n");
print('var bar = new RGraph.Bar('.cvs1.', ['.$data_string.'])' . "\n\n");
print('.Set(\'labels\',[\'1\',\'2\',\'3\',\'4\',\'5\',\'6\',\'7\',\'8\',\'9\',\'10\',\'11\',\'12\',\'13\',\'14\'])'. "\n\n");
print(' .Set(\'colors\', [\'Gradient(#94f776:#50B332:#B1E59F)\', \'Gradient(#94f776:#50B332:#B1E59F)\', \'Gradient(#f2a011:#f2a011:#f2a011:#f2a011)\'])'. "\n\n");
print('.Set(\'hmargin\', 15)'. "\n\n");
print('.Set(\'strokestyle\', \'white\')'. "\n\n");
print('.Set(\'linewidth\', 1)'. "\n\n");
print('.Set(\'shadow\', true)'. "\n\n");
print('.Set(\'shadow.color\', \'#ccc\')'. "\n\n");
print('.Set(\'shadow.offsetx\', 0)'. "\n\n");
print('.Set(\'shadow.offsety\', 0)'. "\n\n");
print('.Set(\'shadow.blur\', 10)'. "\n\n");
print('.Set(\'ymax\', 5)'. "\n\n");
print('.Set(\'colors.sequential\', true)'. "\n\n");
print('.Draw();'. "\n\n");
print('}'. "\n\n");
print('</script>'. "\n\n");

print('var bar = new RGraph.Bar('.cvs1.', ['.$data_string.'])' . "\n\n"); 是从数据库获取数据的代码。我曾尝试编写简单的 php for 甚至 foreach 循环来打印颜色,但它没有用。代码看起来像这样

foreach($data_string as $param)
if ($param<1){
    return(' .Set(\'colors\', [\'Gradient(#FF0000:#FF0000:#FF0000)\'])'. "\n\n");
}
else if($param<=2){
    return(' .Set(\'colors\', [\'Gradient(#f2a011:#f2a011:#f2a011:#f2a011)\'])'. "\n\n");
}
else
    return(' .Set(\'colors\', [\'Gradient(#94f776:#50B332:#B1E59F)\'])'. "\n\n");
}

我确信为 foreach 循环准备数据的代码很好,因为我用它来显示 HTML 表中数据的颜色。有什么解决办法

4

1 回答 1

0

PHP:

<?php
    $colors = array();

    foreach($data_string as $param) {
        if ($param < 1) {
            $colors[] = 'red';
        }

        if ($param > 3) {
            $colors[] = 'green';
        }
    }

    $colors_str = implode(', ', $colors);
?>

JavaScript

obj.Set('colors', [ <?php echo $colors_str; ?> ]);

PS。如果您切换到 HTML 模式,您将不需要在 PHP 代码中对引号进行太多转义。或者跨越多行字符串 - 并谨慎使用引号。像这样:

PHP:

<?php
    print("obj.Set('colors', ['red', green', 'blue'])\n\n");
?>
于 2014-01-20T10:40:31.733 回答