如何以可绘制格式输出 PHP 结果
How to output PHP result in plottable format
我正在尝试使用 https://plot.ly/javascript/ 绘制来自 MySQL
数据库的 PHP
输出。我需要像这样格式化输出 -
var data = [
{
x: ['giraffes', 'orangutans', 'monkeys'],
y: [20, 14, 23],
type: 'bar'
}
];
这是我目前用来获取输出的代码 -
#PHP
$x = array();
$y = array();
while($query_result = $result->fetch_assoc()) {
$x[] = $query_result['Animal'];
$y[] = $query_result['Count'];
}
print_r($y);
#Javascript
$.get('../assets/php/Animals.php', function(data) {
Plotly.newPlot('AnimalChart', data);
});
但是它returns这样的数据-
Array
(
[0] => 20
[1] => 14
[2] => 23
)
我也试过这样json_encode
-
$rows = array();
while($query_result = $result->fetch_assoc()) {
$rows[] = $query_result;
}
echo json_encode($rows);
但输出是这样的,与绘图预期的格式不匹配 -
[{"Animal":"giraffes","Count":"20"},
{"Animal":"orangutans","Count":"14"},
{"Animal":"monkeys","Count":"23"}]
在这两种情况下,Plot.ly
returns 一个错误,这就是为什么我认为它需要像第一个例子一样格式化。
Uncaught TypeError: Cannot read property 'selectAll' of undefined
你的数据不只是 $x
你需要这样的东西:
$x = array();
$y = array();
while($query_result = $result->fetch_assoc()) {
$x[] = $query_result['Animal'];
$y[] = $query_result['Count'];
}
$data = [ [
"x" => $x,
"y" => $y,
"type" => "bar"
] ];
echo json_encode($data);
您的 JS 还需要使用正确的数据类型:
$.get('../assets/php/Animals.php', null, function(data) {
Plotly.newPlot('AnimalChart', data);
}, "json");
我正在尝试使用 https://plot.ly/javascript/ 绘制来自 MySQL
数据库的 PHP
输出。我需要像这样格式化输出 -
var data = [
{
x: ['giraffes', 'orangutans', 'monkeys'],
y: [20, 14, 23],
type: 'bar'
}
];
这是我目前用来获取输出的代码 -
#PHP
$x = array();
$y = array();
while($query_result = $result->fetch_assoc()) {
$x[] = $query_result['Animal'];
$y[] = $query_result['Count'];
}
print_r($y);
#Javascript
$.get('../assets/php/Animals.php', function(data) {
Plotly.newPlot('AnimalChart', data);
});
但是它returns这样的数据-
Array
(
[0] => 20
[1] => 14
[2] => 23
)
我也试过这样json_encode
-
$rows = array();
while($query_result = $result->fetch_assoc()) {
$rows[] = $query_result;
}
echo json_encode($rows);
但输出是这样的,与绘图预期的格式不匹配 -
[{"Animal":"giraffes","Count":"20"},
{"Animal":"orangutans","Count":"14"},
{"Animal":"monkeys","Count":"23"}]
在这两种情况下,Plot.ly
returns 一个错误,这就是为什么我认为它需要像第一个例子一样格式化。
Uncaught TypeError: Cannot read property 'selectAll' of undefined
你的数据不只是 $x
你需要这样的东西:
$x = array();
$y = array();
while($query_result = $result->fetch_assoc()) {
$x[] = $query_result['Animal'];
$y[] = $query_result['Count'];
}
$data = [ [
"x" => $x,
"y" => $y,
"type" => "bar"
] ];
echo json_encode($data);
您的 JS 还需要使用正确的数据类型:
$.get('../assets/php/Animals.php', null, function(data) {
Plotly.newPlot('AnimalChart', data);
}, "json");