簡體   English   中英

無法在Highcharts中的多列mysql數組上顯示x軸標簽

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

我有一個mysql數據庫,其中包含隨時間捕獲的多列功率值,第一列捕獲了時間。 我想繪制功率值並在Highcharts圖表的x軸上顯示一天中的時間。 我目前能夠在y軸上顯示多個功率值,但是我無法獲取一天中的時間在圖表上顯示。 這是部分起作用的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);
?>

有人可以告訴我如何更改代碼以正確地傳遞“時間”列中的值嗎?

這是當前圖表的外觀:

組合功率值

當我對PHP進行更改以將'Energy_Date'字段添加到傳遞給Highcharts的數組中(如下所示)時,將生成一個空白圖表。

該數組由如下所示的字段組成(時間戳和功率讀數,由句點分隔:

“ 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);
?>

接收此數組的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>

我將控制台語句添加到js的底部,如下所示:

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

這是PHP版本1(顯示圖形的版本)在瀏覽器控制台中顯示的內容。

瀏覽器控制台1

這是PHP版本2(給出空白圖表的版本)在瀏覽器控制台中顯示的內容。

瀏覽器控制台2

感謝您的有用建議。 我將while循環更改為如下形式:

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

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]}]

現在,從控制台傳遞到Highcharts的數據如下所示:

瀏覽器控制台3

圖表仍然錯誤:x軸未顯示時間戳,並且圖表不正確。 誰能建議如何更改PHP或html來更正此問題?

好的,我已經更新了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']];
}

PHP輸出現在看起來像這樣:

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

現在該圖表顯示每個功率值的UTC時間戳。

您正在編寫包含許多重復組件的大量代碼。 我已花時間干燥您的方法。 最佳實踐是盡量減少對數據庫的調用,因此我設法將您的查詢合並為一個簡單的選擇。

從理論上講,您只需修改$colnames_labels即可修改HighChart。 我已經寫了一些內聯評論,以幫助您了解我的摘要的功能。 我寫了一些基本的錯誤檢查,以幫助您調試是否失敗。

代碼:(未經測試)

$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