[英]How to prevent months from repeating itself in a javascript chart using php data?
我将此网站作为参考,以了解如何使用数据库中的PHP数据动态创建图表。 http://www.chartjs.org/
所以现在我用一些php代码替换了一些数据后有了这段代码。
<?php
$query = "SELECT * from `users` WHERE firstName = '$name' OR lastName = '$name' LIMIT 1";
$result = mysql_query($query); //<<<
$row = mysql_fetch_assoc($result);
$userid = $row['id'];
echo mysql_error();
$sql = "SELECT * FROM history WHERE userid = '$userid' ORDER BY `date` ASC";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$pointData[] = (int)$row["points"];
$dateData[] = date("d M", $row["date"] );
}
?>
<script>
var data = {
labels : <?php echo json_encode($dateData); ?>,
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : <?php echo json_encode($pointData); ?>
}
]
}
var graphOptions =
{
bezierCurve: false,
scaleOverride: true,
scaleSteps: <?php echo max($pointData); ?>,
scaleStepWidth: 1,
scaleStartValue: 0
}
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx).Line(data, graphOptions);
</script>
如您所见,一切都是通过脚本完成的,但是问题是这样的。
重复的月份使数据看起来很难读取。 每当将点添加到这样的特定ID时,我都会使用具有时间元组的表中的数据制作此表。
那么,如何停止几个月的重复? 是否是因为UNIX时间戳记也记录了几天? 如果是这样,我该如何制止呢?
根据您的评论,使用月度显示而不是单个日期,我将首先生成所有月份的线性比例,然后将所有点添加到其中(您可以对天,年等进行相同的操作)。
就像是:
$months = array();
// using months for just one year, but you could easily adapt it for multiple years
for ($i = 1; $i <= 12; $i++)
{
$months[$i] = 0; // set the initial count to 0
}
// add the points to the appropiate months
while($row = mysql_fetch_array($result))
{
$cur_month = date('n', $row["date"]);
$months[$cur_month] += (int) $row["points"];
}
// your keys are the months and the values the total number of points
$dateData = array_keys($months);
$pointData = array_values($months);
现在,您只需在水平轴上显示月份号,即可轻松进行调整。 还要注意,您可以缩短此时间,我只是使用了array_keys
和array_values
类的东西来显示正在发生的事情以及$months
数组与代码的关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.