简体   繁体   English

无法在Highcharts中的多列mysql数组上显示x轴标签

[英]Unable to display x-axis labels on multi-column mysql array in Highcharts

I have a mysql database containing multiple columns of power values captured over time, with time captured in the first column. 我有一个mysql数据库,其中包含随时间捕获的多列功率值,第一列捕获了时间。 I would like to plot the power values and display the time of day on the x-axis of a Highcharts chart. 我想绘制功率值并在Highcharts图表的x轴上显示一天中的时间。 I am currently able to display the multiple Power values on the y-axis but I am unable to get the time of day to display on the chart. 我目前能够在y轴上显示多个功率值,但是我无法获取一天中的时间在图表上显示。 Here is the PHP code that partially works: 这是部分起作用的PHP代码:

<?php
// Connect to database
$con = mysqli_connect("localhost","userid","passwd","power_readings");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// Set the variable $rows to the columns Energy_Date and Total_watts
$query = mysqli_query($con,"SELECT Energy_Date,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
  $rows['data'][] = $tmp['Total_watts'];
}

// Set the variable $rows1 to the columns Energy_Date and Power_watts
$query = mysqli_query($con,"SELECT Energy_Date,Power_watts FROM combined_readings");
$rows1 = array();
$rows1['name'] = 'Neurio_watts';
while($tmp = mysqli_fetch_array($query)) {
    $rows1['data'][] = $tmp['Power_watts'];
}

// Set the variable $rows2 to the columns Energy_Date and Solar_watts
$query = mysqli_query($con,"SELECT Energy_Date,Solar_watts FROM combined_readings");
$rows2 = array();
$rows2['name'] = 'Solar_watts';
while($tmp = mysqli_fetch_array($query)) {
    $rows2['data'][] = $tmp['Solar_watts'];
}

$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);

print json_encode($result, JSON_NUMERIC_CHECK);

mysqli_close($con);
?>

Can someone tell me how to change the code to pass the values from the time of day column properly? 有人可以告诉我如何更改代码以正确地传递“时间”列中的值吗?

Here is what the chart currently looks like: 这是当前图表的外观:

组合功率值

When I made changes to the PHP to add the 'Energy_Date' field to the array passed to Highcharts (shown below) it results in a blank chart. 当我对PHP进行更改以将'Energy_Date'字段添加到传递给Highcharts的数组中(如下所示)时,将生成一个空白图表。

The array consists of fields that look like this (a time stamp followed by a power reading, separated by period: 该数组由如下所示的字段组成(时间戳和功率读数,由句点分隔:

"2018-02-21 16:56:00.052","2018-02-21 16:59:00.052","2018-02-21 17:02:00.039","2018-02-21 17:05:00.039","2018-02-21 17:08:00.039" “ 2018-02-21 16:56:00.052”,“ 2018-02-21 16:59:00.052”,“ 2018-02-21 17:02:00.039”,“ 2018-02-21 17:05:00.039 “,” 2018-02-21 17:08:00.039“

<?php
// Connect to database
$con = mysqli_connect("localhost","userid","passwd","power_readings");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// Set the variable $rows to the columns Energy_Date and Total_watts
$query = mysqli_query($con,"SELECT Energy_Date,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
  $rows['data'][] = $tmp['Energy_Date'].$tmp['Total_watts'];
}

// Set the variable $rows1 to the columns Energy_Date and Power_watts
$query = mysqli_query($con,"SELECT Energy_Date,Power_watts FROM combined_readings");
$rows1 = array();
$rows1['name'] = 'Neurio_watts';
while($tmp = mysqli_fetch_array($query)) {
    $rows1['data'][] = $tmp['Energy_Date'].$tmp['Power_watts'];
}

// Set the variable $rows2 to the columns Energy_Date and Solar_watts
$query = mysqli_query($con,"SELECT Energy_Date,Solar_watts FROM combined_readings");
$rows2 = array();
$rows2['name'] = 'Solar_watts';
while($tmp = mysqli_fetch_array($query)) {
    $rows2['data'][] = $tmp['Energy_Date'].$tmp['Solar_watts'];
}

$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);

print json_encode($result, JSON_NUMERIC_CHECK);

mysqli_close($con);
?>

The html receiving this array looks like this: 接收此数组的html如下所示:

<!DOCTYPE html>
<html lang="en">
<title>Combined Values Graph</title>
<head>
 <meta http-equiv="refresh" content="180">
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <script type="text/javascript">
         $(function () {
             var x_values = [];
             var chart;
             $(document).ready(function() {
                 Highcharts.setOptions({
                     colors: ['#4083e9', '#99ccff', '#00ffff', '#e6e6e6', '#DDDF00', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
                 });

                 $.getJSON("values.php", function(json) {

                     chart = new Highcharts.Chart({
                         chart: {
                             renderTo: 'mygraph',
                             type : 'spline',
                             borderWidth: 1,
                             zoomType: 'x',
                             panning: true,
                             panKey: 'shift',
                             plotShadow: false,
                             marginTop: 100,
                             height: 500,
                             plotBackgroundImage: 'gradient.jpg'
                         },
                         plotOptions: {
                             series: {
                                 fillOpacity: 1
                             }
                         },
                         plotOptions: {
                             series: {
                                marker: {
                                     enabled: false
                                }
                             }
                         },
                         title: {
                             text: 'Combined Power Readings'

                         },
                         subtitle: {
                             text: 'Total = Neurio + Solar Readings in Watts'

                         },
                         xAxis : {
                             title : {
                                 text : 'Time of Day'
                             }
                         },
                         yAxis: {
                             title: {
                                 text: 'Power (watts)'
                             },
                             plotLines: [{
                                 value: 0,
                                 width: 2,
                                 color: '#ff0000',
                                 zIndex:4,
                                 dashStyle: 'ShortDot'
                             }]
                         },
                         tooltip: {
                             formatter: function() {
                                     return '<b>'+ this.series.name +'</b><br/>'+
                                     this.x +': '+ this.y;
                             }
                         },
                         legend: {
                             layout: 'vertical',
                             align: 'right',
                             verticalAlign: 'top',
                             x: -10,
                             y: 120,
                             borderWidth: 1
                         },
                         plotOptions : {
                             spline : {
                                 marker : {
                                     radius : 0,
                                     lineColor : '#666666',
                                     lineWidth : 0
                                 }
                             }
                         },
                         series: json
                         });
                 });

             });

         });
 </script>
 <script src="https://code.highcharts.com/highcharts.src.js"></script>
 <script src="http://code.highcharts.com/modules/exporting.js"></script>

</head>
<body>
<div class="container" style="margin-top:20px">
 <div class="col-md-10">
  <div class="panel panel-primary">
    <div class="panel-body">
     <div id ="mygraph"></div>
    </div>
  </div>
 </div>
</div>
</body>
</html>

I have added the console statement to the bottom of the js like so: 我将控制台语句添加到js的底部,如下所示:

                 series: json
                 });
                 console.log(json);
         });

Here's what is shown in the browser console for PHP version 1 (The version that displays the graphs). 这是PHP版本1(显示图形的版本)在浏览器控制台中显示的内容。

Browser console 1 浏览器控制台1

Here's what is shown in the browser console for PHP version 2 (The version that gives a blank chart). 这是PHP版本2(给出空白图表的版本)在浏览器控制台中显示的内容。

Browser console 2 浏览器控制台2

Thanks for your helpful suggestions. 感谢您的有用建议。 I have changed the while loops to look like this: 我将while循环更改为如下形式:

while($tmp = mysqli_fetch_array($query)) {
  $rows['data'][] = $tmp['Energy_UTC'];
  $rows['data'][] = $tmp['Total_watts'];
}

The output of the PHP now looks like this: PHP的输出现在如下所示:

[{"name":"Total_watts","data":[1519315164,93,1519315344,354]},{"name":"Neurio_watts","data":[1519315164,76,1519315344,309]},{"name":"Solar_watts","data":[1519315164,17,1519315344,45]}]

The data being passed to Highcharts (from the console) now looks like this: 现在,从控制台传递到Highcharts的数据如下所示:

Browser console 3 浏览器控制台3

The chart is still wrong: the x-axis is not showing the timestamps and the chart is incorrect. 图表仍然错误:x轴未显示时间戳,并且图表不正确。 Can anyone suggest how to change the PHP or html to correct this? 谁能建议如何更改PHP或html来更正此问题?

OK, I have updated the while loops to look like this: 好的,我已经更新了while循环,如下所示:

$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
  $rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}

The PHP output now looks like this: PHP输出现在看起来像这样:

[{"name":"Total_watts","data":[[1519387869,423],[1519388049,423],[1519388229,332],[1519388410,514],[1519388590,514]... [{“ name”:“ Total_watts”,“ data”:[[1519387869,423],[1519388049,423],[1519388229,332],[1519388410,514],[1519388590,514] ...

and the chart is now displaying UTC timestamps for each power value. 现在该图表显示每个功率值的UTC时间戳。

You are writing a large block of code with many duplicated components. 您正在编写包含许多重复组件的大量代码。 I've taken the time to DRY your method. 我已花时间干燥您的方法。 It is best practice to minimize calls to the database, so I've managed to combine your queries into one simple select. 最佳实践是尽量减少对数据库的调用,因此我设法将您的查询合并为一个简单的选择。

Theoretically, you will only need to modify $colnames_labels to modify your HighChart. 从理论上讲,您只需修改$colnames_labels即可修改HighChart。 I have written inline comments to help you to understand what my snippet does. 我已经写了一些内联评论,以帮助您了解我的摘要的功能。 I have written some basic error checks to help you to debug if anything fails. 我写了一些基本的错误检查,以帮助您调试是否失败。

Code: (untested) 代码:(未经测试)

$colnames_labels=[
    'Total_watts'=>'Total_watts',
    'Power_watts'=>'Neurio_watts',
    'Solar_watts'=>'Solar_watts'
];

$select_clause_ext='';                            // declare as empty string to allow concatenation
foreach($colnames_labels as $colname=>$label){
    $data[]=['name'=>$label];                     // pre-populate final array with name values
    // generates: [0=>['name'=>'Total_watts'],1=>['name'=>'Neurio_watts'],2=>['Solar_watts']]
    $select_clause_ext.=",$colname";
    // generates: ",Total_watts,Power_watts,Solar_watts"
}

$subarray_indexes=array_flip(array_keys($colnames_label));  // this will route resultset data to the correct subarray
// generates: ['Total_watts'=>0,'Power_watts'=>1,'Solar_watts'=>2]

if(!$result=mysqli_query($con,"SELECT UNIX_TIMESTAMP(Energy_Date) AS Stamp{$select_clause_ext} FROM combined_readings ORDER BY Energy_Date")){
    $data=[['name'=>'Syntax Error (query error)','data'=>[0,0]];  // overwrite data with error message & maintain expected format
}elseif(!mysqli_num_rows($result)){
    $data=[['name'=>'Logic Error (no rows)','data'=>[0,0]];
}else{
    while($row=mysqli_fetch_assoc($result)){
        foreach($subarray_indexes as $i=>$col){
            $data[$i]['data'][]=[$row['Stamp'],$row[$col]];  // store [stamp,watts] data in appropriate subarrays
        }
    }
}

echo json_encode($data,JSON_NUMERIC_CHECK);  // Convert to json (while encoding numeric strings as numbers) and print to screen

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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