这是我的PHP代码。最终echo语句的输出是[$ numbers [0],$ numbers [1],$ numbers [2],$ numbers [3],$ numbers [4],$ numbers [5]]。这正是我所追求的。但是,当我尝试将其传递给javascript变量以生成rgraph图表时,它无法正常工作。结束脚本标签不合适。请帮忙。
public function badgers(){
global $badgersData;
global $dynamicString;
include("dal/database.php");
$numbers = array();
$result=mysql_query("SELECT Id, count(TimeCode) FROM animals
WHERE TimeCode IN ('A','B','C','D','E','F') AND Name='badger' group by TimeCode" )or die(mysql_error());
while(($row = mysql_fetch_assoc($result))){
$numbers[] = $row['count(TimeCode)'];
};
global $getKeys;
$str = '';
$getKeys;
$keys = array_keys($numbers);
$arraySize = count($numbers);
for($i=0;$i<$arraySize;$i++){
$getKeys = $keys[$i];
}
for($i = 0; $i <= $getKeys; $i++ ) {
$str .= '$numbers['. $i . '],';
}
$dynamicString= rtrim($str,",");
echo $badgersData = '['.$dynamicString.']';
}
<canvas id="badgerBarChartCanvas" width="600px" height="400px">Your browser does not have canvas support</canvas>
<script>
function badgers()
{
var badgers = eval("<?php echo $badgersData; ?>"); // variable in question
var badgersBarChart = new RGraph.Bar('badgerBarChartCanvas', badgers);
var colors = ['pink','navy','gray','yellow','purple','black'];
RGraph.Effects.Bar.Grow(badgersBarChart, {'duration': 5000}); }
badgers();
答案 0 :(得分:0)
我不知道我怀疑的RGraph图表,所有你需要做的就是类似
<?php
$numbers = [1,2,3,4];
?>
<script>
var badgers = <?php echo json_encode($numbers);?>;
// ...
</script>
如果你 read the manual ,那真的不太难!
这是经过测试的:
<body>
<script src="js/rgraph/RGraph.common.core.js"></script> // Always required
<script src="js/rgraph/RGraph.common.dynamic.js"></script> // Only required for dynamic features
<script src="js/rgraph/RGraph.common.tooltips.js"></script> // Only required for tooltips
<script src="js/rgraph/RGraph.bar.js"></script> // Required for Bar charts
<canvas id="badgerBarChartCanvas" width="600px" height="400px">Your browser does not have canvas support</canvas>
<?php
$numbers =
[ [ 10, 20], [15, 8], [11, 16], [9, 12], [18, 17], [13, 14],
[ 11, 16], [9, 12], [18, 17], [13, 14], [10, 20], [15, 8]
];
$labels = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec'];
?>
<script>
var badgersData = <?php echo json_encode($numbers);?>;
var badgersLabels = <?php echo json_encode($labels);?>;
function drawBadgersBar()
{
var badgersBarChart = new RGraph.Bar(
{ id : 'badgerBarChartCanvas',
data : badgersData,
options:
{
labels: badgersLabels,
colors: ['pink','navy','gray','yellow','purple','black']
}
});
badgersBarChart.grow(badgersBarChart, {'duration': 5000});
}
drawBadgersBar();
</script>
</body>