[英]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.