将JSON编码的PHP变量传递给HighCharts

时间:2016-04-21 20:59:50

标签: javascript php mysql json highcharts

我试图将PHP变量中的JSON编码的MySQL结果集插入到Highcharts脚本中。

我已经成功地将PHP结果列表从PHP变量插入到不同实例中的Highcharts,并通过SQL Select语句中的Group Concatenating逗号和撇号格式化为Highchart可接受的数据(这是一种肮脏但有效的方法)。我现在的目标是让我的图表在工具提示中显示元数据,这是我无法工作的,但我认为我与我所拥有的很接近。

-

这是用于从MySQL数据库检索数据并且JSON对其进行编码的PHP脚本:

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

以下是我尝试使用自己的数据进行重新构建的基本Highcharts脚本(功能正常)(可在this JSfiddle找到)。

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

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

You need to convert your output to a Javascript object or else javascript will consider it a string and read it like "['Main Item', 'Second Item', 'Third Item']" instead of an object. You can do this using the JSON.Parse() function in javascript.

Try to replace [(a dymanically-generated list of dates)] with something like JSON.Parse("<?php echo $raw_json; ?>");

答案 1 :(得分:0)

成功:可能不是最佳实践方式,但我做到了。

行情无法单方面应用。我使用str_replace方法从JSON输出中删除双引号字符,并使用CONCAT SQL函数将单引号字符添加到字符串中,我想要它们。

例如,一个日期保留为2015-11-15,而不是2015-11-15&#39;被解释为2015减11减15,因此日期必须用引号括起来。另一方面,&#34; y:&#34;如果引号,则不会将值解析为条形大小。所以报价必须单独应用。 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>