我正在尝试使用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);
});
但它返回的数据是这样的 -
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
都会返回错误,这就是为什么我认为它需要像第一个示例一样进行格式化。
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 还需要使用正确的 dataType:
$.get('../assets/php/Animals.php', null, function(data) {
Plotly.newPlot('AnimalChart', data);
}, "json");
关于javascript - 如何以可绘图格式输出 PHP 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36625905/