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

Posted

技术标签:

【中文标题】将 JSON 编码的 PHP 变量传递给 HighCharts【英文标题】:Pass JSON-encoded PHP Variable to HighCharts 【发布时间】:2016-08-15 06:57:24 【问题描述】:

我正在尝试将来自 php 变量的 JSON 编码 mysql 结果集插入到 Highcharts 脚本中。

我已成功将 MySQL 结果列表从 PHP 变量插入到不同实例中的 Highcharts,通过在 SQL Select 语句中连接逗号和撇号将其格式化为 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] 

下面是我尝试使用我自己的数据(在thisJSfiddle 找到)改造的基本 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>

提前感谢您的帮助!

【问题讨论】:

无论你想在工具提示中显示什么,都可以设置为字符串,因为它毕竟会显示为字符串。您不需要从 json 数据中删除引号。 Here 是更新的小提琴,看看吧。 感谢您的帮助;但是,这告诉了我很多,“y:”值必须在没有引号的情况下产生。我会尽力做到这一点。将根据结果更新帖子。 【参考方案1】:

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

不能单方面应用报价。我使用 str_replace 方法从 JSON 输出中去除双引号字符,并使用 CONCAT SQL 函数将单引号字符添加到我想要的字符串中。

例如,保留为 2015-11-15 而不是“2015-11-15”的日期将被解释为 2015 减 11 减 15,因此日期必须用引号引起来。另一方面,如果在其周围有 are 引号,则“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>

【讨论】:

还有另一种可能更简单的方法。将您的代码与问题中的代码保持一致,以便 json 输出全部用引号引起来。然后在将其设置为 highcharts 系列数据之前,只需对其进行一次迭代并将“y”值解析为一个数字。属性名称 y 仍然可以用引号引起来,它会起作用。【参考方案2】:

您需要将输出转换为 Javascript 对象,否则 javascript 会将其视为 string 并像 "['Main Item', 'Second Item', 'Third Item']" 一样读取它而不是对象。您可以使用 javascript 中的 JSON.Parse() 函数来执行此操作。

尝试将[(a dymanically-generated list of dates)] 替换为JSON.Parse("&lt;?php echo $raw_json; ?&gt;"); 之类的东西

【讨论】:

他在问题中添加的 raw_json 的值对我来说不像字符串,看起来像 javascript 对象。 如果您在 PHP 中使用混合 HTML 回显 json 对象 - 它将作为字符串输出,除非您更改标头 mime 类型,或者仅在执行 ajax 请求时输出 json 数据。在您的示例 ['Main Item', 'Second Item', 'Third Item'] 中,如果它是由 PHP 输出的,则读作“['Main Item', 'Second Item', 'Third Item']”。因此,您必须使用 JSON.Parse() 将其转换为对象。您可以使用 console.log() 来确认这一点。

以上是关于将 JSON 编码的 PHP 变量传递给 HighCharts的主要内容,如果未能解决你的问题,请参考以下文章

通过 POST 将 JSON 编码的变量从 PHP 传递到 Javascript

将php变量传递给角度

将全局变量传递给ajax函数,发布到php,保存到数据库

通过 GET json 传递给 ajax jquery,

如何将c#中的变量传递给前端

Swift:如何将可编码类型作为函数输入传递给编码或解码 json