Boa*_*rdy 3 php json google-visualization
我正在开发一个项目,我正在使用Google Charting API,我想使用json填充图表来构建数据表.
作为一个测试,我试图在尝试使用数据库中的动态数据之前构建一个简单的数组,但是我遇到了以正确格式获取json的问题.
在谷歌文档中,它说json内容应该在以下内容:
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}
Run Code Online (Sandbox Code Playgroud)
我正在调用一个返回json代码的函数.
下面是调用函数的方法
print json_encode(test());
Run Code Online (Sandbox Code Playgroud)
而测试功能是
function test()
{
$array = array();
$array['cols'][] = "20-01-13";
$array['cols'][] = "21-01-13";
$array['cols'][] = "22-01-13";
$array['rows'][] = 22;
$array['rows'][] = 26;
$array['rows'][] = 12;
return $array;
}
Run Code Online (Sandbox Code Playgroud)
生成图表的javascript如下
<script>
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "loadGraph.php",
dataType:"json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('lineGraph'));
chart.draw(data, {width: 400, height: 240});
}
</script>
Run Code Online (Sandbox Code Playgroud)
当我回显json时,它将以下列格式返回
{"cols":["20-01-13","21-01-13","22-01-13"],"rows":[22,26,12]}
Run Code Online (Sandbox Code Playgroud)
如果我尝试将此用于谷歌图表的数据集,我会收到以下消息
Cannot read property of '1' of undefined
Run Code Online (Sandbox Code Playgroud)
我只是构建一个简单的折线图,它只包含沿x轴的日期和沿y轴在该日期发生的事件的次数.
我如何构建数组以使其以正确的格式为谷歌api图表.
感谢您的任何帮助,您可以提供.
您需要为cols 指定参数类型.请参阅Google Charts JSON格式
您的PHP代码应类似于:
function test()
{
$array['cols'][] = array('type' => 'string');
$array['cols'][] = array('type' => 'string');
$array['cols'][] = array('type' => 'string');
$array['rows'][] = array('c' => array( array('v'=>'20-01-13'), array('v'=>22)) );
$array['rows'][] = array('c' => array( array('v'=>'21-01-13'), array('v'=>26)));
$array['rows'][] = array('c' => array( array('v'=>'22-01-13'), array('v'=>12)));
return $array;
}
print json_encode(test());
Run Code Online (Sandbox Code Playgroud)
你的json代码看起来更像是:
{
"cols": [
{"type": "string"},
{"type": "string"},
{"type": "string"}
],
"rows": [
{"c":[{"v":"20-01-13"}, {"v":22} ]},
{"c":[{"v":"21-01-13"}, {"v":26} ]},
{"c":[{"v":"22-01-13"}, {"v":12} ]}
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14524 次 |
| 最近记录: |