[英]How to output PHP result in plottable format
I am trying to use https://plot.ly/javascript/ for plotting PHP
output from a MySQL
database. 我正在尝试使用https://plot.ly/javascript/从
MySQL
数据库绘制PHP
输出。 I need the output to be formatted like this - 我需要这样格式化输出-
var data = [
{
x: ['giraffes', 'orangutans', 'monkeys'],
y: [20, 14, 23],
type: 'bar'
}
];
This is currently the code I am using to get my output - 目前这是我用来获取输出的代码-
#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);
});
But it returns the data like this - 但它会返回这样的数据-
Array
(
[0] => 20
[1] => 14
[2] => 23
)
I've also tried to json_encode
like this - 我也尝试过像这样
json_encode
$rows = array();
while($query_result = $result->fetch_assoc()) {
$rows[] = $query_result;
}
echo json_encode($rows);
But the output is this, which does not match the format expected for the plot - 但是输出是这样,它与绘图的预期格式不匹配-
[{"Animal":"giraffes","Count":"20"},
{"Animal":"orangutans","Count":"14"},
{"Animal":"monkeys","Count":"23"}]
In both scenarios, Plot.ly
returns an error, which is why I think it needs to be formatted like the first example. 在这两种情况下,
Plot.ly
返回一个错误,这就是为什么我认为它需要像第一个示例一样进行格式化的原因。
Uncaught TypeError: Cannot read property 'selectAll' of undefined
未捕获的TypeError:无法读取未定义的属性'selectAll'
Your data is not just $x
you need something like: 您的数据不仅仅是
$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);
Your JS also needs to use the correct dataType: 您的JS还需要使用正确的dataType:
$.get('../assets/php/Animals.php', null, function(data) {
Plotly.newPlot('AnimalChart', data);
}, "json");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.