I am trying to generate a multiple line graph with Highcharts, where each line represents data from a different year, and the x-axis displays the date while the y-axis displays the price.
I have a MySQL database table from which I’m fetching data, and I’m grouping that data by year using PHP. The $chart_data array holds the data grouped by year, and the name key holds the year value while the data key holds an array of timestamp and price pairs.
I’ve included the PHP code I’m using to generate the chart, and it successfully generates the graph, but the data is not displaying correctly. The graph shows all the years on the same line instead of each year on its own line.
I’m expecting the graph to look like the one in this reference image Demo Graph Screenshot, with each year displayed on its own line.
I’m new to Highcharts and not sure how to adjust the code to display the graph correctly. Can anyone help me with this issue? Thank you in advance!
Here is the code I’m using to generate the chart:
// SQL Query…
<?php
$chart_record = $wpdb->get_results($SQL_ALL_TBL_FOR_CHART);
$chart_title = '';
if ($chart_record){
$row = $chart_record[0];
$chart_title = $row->var_name . ' | ' . $row->type_name;
$chart_data = array();
$grouped_data = array();
foreach ($chart_record as $row) {
$year = $row->year;
if (!isset($grouped_data[$year])) {
$grouped_data[$year] = array();
}
$date = new DateTime($row->rptl_date);
$timestamp = $date->getTimestamp() * 1000;
$grouped_data[$year][] = array(
'x' => $timestamp,
'y' => (int) $row->rptl_price
);
}
foreach ($grouped_data as $year => $year_data) {
$chart_data[] = array(
'name' => $year,
'data' => $year_data
);
}
}
?>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div class="container">
<div id="chart-container"></div>
</div>
<script>
Highcharts.chart('chart-container', {
chart: {
type: 'line'
},
title: {
text: '<?php echo $chart_title; ?>'
},
xAxis: {
type: 'datetime',
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Price'
}
},
series: [
<?php foreach ($chart_data as $year_data): ?> {
name: '<?php echo $year_data["name"]; ?>',
data: [
<?php foreach ($year_data["data"] as $data): ?>[<?php echo $data["x"]*1000; ?>,
<?php echo $data["y"]; ?>],
<?php endforeach; ?>
]
},
<?php endforeach; ?>
]
});
</script>
The output of this code is:
I was expecting this code to generate the graph as I have provided the reference image 
But the issue is clear to you. Please help me with this problem. Thank you!
