簡體   English   中英

將JSON編碼的PHP變量傳遞給HighCharts

[英]Pass JSON-encoded PHP Variable to HighCharts

我正在嘗試將PHP變量中的JSON編碼的MySQL結果集插入到Highcharts腳本中。

我已經成功地將MySQL結果列表從PHP變量插入到另一個實例的Highcharts中,並通過在SQL Select語句中用逗號和撇號進行組連接將其格式化為Highchart可接受的數據(這是一種骯臟但有效的方法)。 我現在的目標是使圖表在工具提示中顯示元數據,我無法使用它,但是我認為我已經掌握了這些內容。

-

這是PHP腳本,用於從MySQL數據庫檢索數據並對其進行JSON編碼:

$mysqli = new mysqli('localhost','username','password','database');

$myArray = array();

if ($result = $mysqli->query("
SELECT
time_minutes.minutes*60+time_seconds.seconds AS y,
run_date.id AS ID,
run_date.date AS RunDate,
run_temp.temperature AS Temperature,
run_conditions.weather AS Conditions,
run_hydration.hydration_level AS Hydration
FROM run_conditions, run_date, run_hydration, run_notes, run_temp, time_minutes, time_seconds
WHERE run_date.id = run_conditions.id
AND run_date.id = run_hydration.id
AND run_date.id = run_notes.id
AND run_date.id = run_temp.id
AND run_date.id = time_minutes.id
AND run_date.id = time_seconds.id
")) {

    while($row = $result->fetch_array(MYSQL_ASSOC)) {
            $myArray[] = $row;
    }
}

$raw_json = json_encode($myArray);

$json_without_quotes = str_replace('"', "", $raw_json);

$result->close();
$mysqli->close();
?>

y值是我希望的條形高度; 其余的是元數據(溫度,條件等),我想出現在工具提示中。

raw_json輸出如下所示:

[{"y":"1500.00",
"ID":"1",
"RunDate":"2015-10-19",
"Temperature":"87",
"Conditions":"Humid and hot",
"Hydration":"8"},
{"y":"1474.48",
"ID":"2",
"RunDate":"2015-10-21",
"Temperature":"80",
"Conditions":"Light rain",
"Hydration":"9"},
{"y":"1442.01",
"ID":"3",
"RunDate":"2015-10-22",
"Temperature":"82",
"Conditions":"Sunny",
"Hydration":"4"}]

json_without_quotes輸出看起來像這樣:

[{y:1500.00,
ID:1,
RunDate:2015-10-19,
Temperature:87,
Conditions:Humid and hot,
Hydration:8},
{y:1474.48,
ID:2,
RunDate:2015-10-21,
Temperature:80,
Conditions:Light rain,
Hydration:9},
{y:1442.01,
ID:3,
RunDate:2015-10-22,
Temperature:82,
Conditions:Sunny,
Hydration:4}] 

下面是我嘗試使用自己的數據(在 JSfiddle中找到)重塑的基本Highcharts腳本(具有功能)。

<script>
$(function () {
    var chart = new Highcharts.Chart({
        chart: {
            renderTo: 'chartchartchart',
            type: 'column'
        },
        xAxis: {
            categories: [(a dymanically-generated list of dates)]
        },
        series: [{
            data: [{

這是我要插入json_without_quotes變量的地方; 以下數據的格式正確,但是我注意到它僅包含整數; 必須更改某些內容以使其接受字符串作為參數,但是我不知道必須更改什么。

                y: 3,
                locked: 1,
                unlocked: 1,
                potential: 1,
            }, {
                y: 5,
                locked: 2,
                unlocked: 1,
                potential: 3,
            }, {
                y: 7,
                locked: 3,
                unlocked: 1,
                potential: 3,
            }]
        }],
        tooltip: {
            formatter: function() {return ' ' +
                'Locked: ' + this.point.locked + '<br />' +
                'Unlocked: ' + this.point.unlocked + '<br />' +
                'Potential: ' + this.point.potential;
            }
        }
    });
});
</script>
<div id="chartchartchart" style="height: 400px"></div>

在此先感謝您的幫助!

您需要將輸出轉換為Javascript對象,否則javascript會將其視為string並像"['Main Item', 'Second Item', 'Third Item']"而不是對象)一樣讀取。 您可以使用javascript中的JSON.Parse()函數執行此操作。

嘗試用類似JSON.Parse("<?php echo $raw_json; ?>");替換[(a dymanically-generated list of dates)] JSON.Parse("<?php echo $raw_json; ?>");

成功:可能不是最佳做法 ,但我做到了。

不能單引號。 我使用str_replace方法從JSON輸出中去除雙引號字符,並使用CONCAT SQL函數在需要的地方向字符串添加單引號字符。

例如,日期保留為2015-11-15而不是'2015-11-15'被解釋為2015減11減15,因此該日期必須用引號引起來。 在另一方面,“Y:”值沒有,如果周圍的引號解析為鋼筋尺寸。 因此,必須單獨使用引號。 MySQL串聯是執行IMO的最簡單方法。

PHP:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<?php

// Open database connection
$mysqli = new mysqli('localhost','username','password','database');

// Get the Date List and format it for the Highchart x-axis labels
$datequery = "
SELECT GROUP_CONCAT( \"'\", run_date.date, \"'\" )
FROM run_date
ORDER BY id
";

$dateresult = $mysqli->query($datequery);

$daterow = $dateresult->fetch_array(MYSQLI_NUM);

print "<pre>";
print_r($daterow);
print "</pre>"; 

$date_list = $daterow[0];
// End of Date List part

// Start of Chart Data to generate bars
$myArray = array();

if ($result = $mysqli->query("
SELECT
time_minutes.minutes*60+time_seconds.seconds AS y,
run_date.id AS ID,
CONCAT(\"'\", time_minutes.minutes, ':', time_seconds.seconds, \"'\") AS RunTime,
run_temp.temperature AS Temperature,
run_hydration.hydration_level AS Hydration,
CONCAT(\"'\", run_notes.note, \"'\") AS Notes,
CONCAT(\"'\", run_date.date, \"'\") AS RunDate
FROM run_conditions, run_date, run_hydration, run_notes, run_temp, time_minutes, time_seconds
WHERE run_date.id = run_conditions.id
AND run_date.id = run_hydration.id
AND run_date.id = run_notes.id
AND run_date.id = run_temp.id
AND run_date.id = time_minutes.id
AND run_date.id = time_seconds.id
")) {

    while($row = $result->fetch_array(MYSQL_ASSOC)) {
            $myArray[] = $row;
    }
}

// End of Bar Chart Part

// Beginning of producing JSON object

$raw_json = json_encode($myArray); // Put the MySQL results into JSON format

$json_without_quotes = str_replace('"', "", $raw_json); // Strip the double-quotes out of the JSON; the SQL concatenates single quotes where they are needed.

 // Print the quote-stripped JSON to test it
echo $json_without_quotes;

// Close the connection, of course
$result->close();
$mysqli->close();
?>

JSON輸出:

[{
y:1500.00,
ID:1,
RunTime:'25:0.00',
Temperature:87,
Hydration:8,
Notes:'Sed sagittis. Nam congue, risus semper porta volutpat, quam pede lobortis ligula, sit amet eleifend pede libero quis orci.',
RunDate:'2015-10-19'},
{y:1474.48,
ID:2,
RunTime:'24:34.48',
Temperature:80,
Hydration:9,
Notes:'Nullam orci pede, venenatis non, sodales sed, tincidunt eu, felis.',
RunDate:'2015-10-21'},
{y:1442.01,
ID:3,
RunTime:'24:2.01',
Temperature:82,
Hydration:4,
Notes:'Duis bibendum. Morbi non quam nec dui luctus rutrum. Nulla tellus.',
RunDate:'2015-10-22'}]

Highcharts腳本:

<script>
$(function () {
    var chart = new Highcharts.Chart({
        chart: {
            renderTo: 'chartdiv',
            type: 'column'
        },
        xAxis: {
            categories: [<?=$date_list?>]
        },
        series: [{
            data: <?=$json_without_quotes?>
        }],
        tooltip: {
            formatter: function() {return ' ' +
                'ID: ' + this.point.ID + '<br />' +
                'Run Date: ' + this.point.RunDate + '<br />' +
                'Temperature: ' + this.point.Temperature + '<br />' +
                'Hydration: ' + this.point.Hydration + '<br />' +
                'Notes: ' + this.point.Notes;
            }
        }
    });
});
</script>
<div id="chartdiv" style="height: 1000px"></div>
</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM