I am working on a project where I am making use of the Google Charting API and I want to populate the chart using json to build the data table.
As a test I am tryin
You need to specify the parameter type for cols. Refer to Google Charts JSON Format
Your PHP code should look similar to:
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());
Your json code would look more like:
{
"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} ]}
]
}
This may come a bit late but anyway, here's what worked for me (needed to create a barchart).
Get the server code to return the json string representing an array e.g. something like:
[{
"score": 12,
"subject": "Computer Graphics"
}, {
"score": 65,
"subject": "Entreprenuership"
}, {
"score": 82,
"subject": "C++Programming"
}]
Parse the string using eval()
or JSON.parse()
to get the JavaScript object.
var chartData = JSON.parse(jsonStringFromServer);
Create a DataTable object as such:
var dTable = new google.visualization.DataTable();
Add columns to the dataTable :
dTable.addColumn('string','Subject');
dTable.addColumn('number','Score');
//more columns if needed...
Loop through the javascript array (chartData
) and for each object in the array, add a new row to the dataTable
:
for(i=0;i<chartData.length;i++){
var currentObj = chartData[i];
dTable.addRow([currentObj.subject,currentObj.score]);
}
//set options for the chart e.g title, width etc
// create the chart ...
it should be like:
array(10) {
[0]=>
array(2) {
[0]=>
string(2) "en"
[1]=>
int(104)
}
[1]=>
array(2) {
[0]=>
string(0) ""
[1]=>
int(70)
}
[2]=>
array(2) {
[0]=>
string(2) "zh"
[1]=>
int(13)
}
[3]=>
array(2) {
[0]=>
string(2) "ru"
[1]=>
int(10)
}
...
then
var data = google.visualization.arrayToDataTable(<?php echo json_encode($our_array); ?>);
var chart = new google.visualization.PieChart(document.getElementById('someId'));
chart.draw(data, options);