简体   繁体   中英

How to prevent months from repeating itself in a javascript chart using php data?

I am using this website as a reference as how to create charts dynamically using PHP data from a database. http://www.chartjs.org/

So now I have this code after replacing some data with some php code.

<?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>

As you can see everything is done through a script, but the problem is this.

The months are being repeated which makes the data look very hard to read. I made this table using data from a table that has a tuple for time whenever a point is added to a certain ID like this.

在此处输入图片说明

So how do I stop the months from repeating itself? Is it because the UNIX timestamp also records days? If so how do I stop that?

Based on your comment, using a monthly display instead of individual days, I would first generate a linear scale of all months and then add all your points to it (you could do the same for days, years, etc.).

Something like:

$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);

Now you just have the month numbers on the horizontal axis, but that can easily be adapted. Also note that you can shorten this, I just used things like array_keys and array_values to show what is happening exactly and how the $months array relates to your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM