我必须为我的学校调查项目实施条形图,我想我差不多完成但没有什么是完美的,这是我的问题。我通过本教程http://www.rgraph.net/docs/bar.html实现了此代码http://www.rgraph.net/docs/integration-with-server-side-scripting.html#mysql,但我遇到了一个问题。我需要绘制图形条取决于它的高度,例如等于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,甚至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表格中的数据颜色。有没有解决方案
答案 0 :(得分: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");
?>