如何重新格式化柱形图的json输出?

时间:2017-09-06 10:17:49

标签: javascript json charts google-visualization

之前我使用Ajax绘制谷歌图表(饼图),图表可以显示,因为它只涉及2列。

现在,我想绘制一个像这样的柱状图。

column chart

这是我的SQL查询:

$sql = "Select count(application_id) as count, application_status,   category_group from mdl_local_jobs_application 
inner join mdl_local_jobs_job on mdl_local_jobs_application.application_jobid = mdl_local_jobs_job.job_id
left join mdl_local_jobs_category on mdl_local_jobs_job.job_categoryid = mdl_local_jobs_category.category_id 
left join mdl_cohort_members on mdl_local_jobs_application.application_applicantid = mdl_cohort_members.userid
left join mdl_local_cohortrole on mdl_cohort_members.cohortid = mdl_local_cohortrole.cohortid
left join mdl_role on mdl_local_cohortrole.roleid = mdl_role.id where shortname = 'graduates'
group by application_status, category_group";

使用以下代码将查询编码为Json输出:

$result_rows = mysql_num_rows($query);
$row_num = 0;

//loop fetching the query into json format
while ($result = mysql_fetch_array($query))
{
$row_num++;
if ($row_num == $result_rows){
  echo "{\"c\":[{\"v\":\"" . $result['application_status'] . "\",\"f\":null},{\"v\":\"" . $result['category_group'] . "\",\"f\":null},{\"v\":" . $result['count'] . ",\"f\":null}]}";
} else {
   echo "{\"c\":[{\"v\":\"" . $result['application_status'] . "\",\"f\":null},{\"v\":\"" . $result['category_group'] . "\",\"f\":null},{\"v\":" . $result['count'] . ",\"f\":null}]}";
}
}


echo " ] }";

这是输出:

{ "cols": [ {"id":"","label":"STATUS","pattern":"","type":"string"}, {"id":"","label":"CATEOGRY","pattern":"","type":"string"}, {"id":"","label":"TOTAL","pattern":"","type":"number"} ], "rows": [ {"c":[{"v":"0","f":null},{"v":"Accounting/Finance","f":null},{"v":2,"f":null}]}{"c":[{"v":"0","f":null},{"v":"Engineering","f":null},{"v":1,"f":null}]} ] } 

但是,谷歌图表无法读取此输出。这是错误。

Error: Invalid JSON string: { "cols": [ {"id":"","label":"STATUS","pattern":"","type":"string"}, {"id":"","label":"CATEOGRY","pattern":"","type":"string"}, {"id":"","label":"TOTAL","pattern":"","type":"number"} ], "rows": [ {"c":[{"v":"0","f":null},{"v":"Accounting/Finance","f":null},{"v":2,"f":null}]}{"c":[{"v":"0","f":null},{"v":"Engineering","f":null},{"v":1,"f":null}]} ] }

我的问题:我想如何重新格式化代码以获得柱形图的输出?

1 个答案:

答案 0 :(得分:0)

需要在每行的末尾添加一个逗号...

if ($row_num == $result_rows){
  echo "{\"c\":[{\"v\":\"" . $result['application_status'] . "\",\"f\":null},{\"v\":\"" . $result['category_group'] . "\",\"f\":null},{\"v\":" . $result['count'] . ",\"f\":null}]},"; // <-- add comma
} else {
  echo "{\"c\":[{\"v\":\"" . $result['application_status'] . "\",\"f\":null},{\"v\":\"" . $result['category_group'] . "\",\"f\":null},{\"v\":" . $result['count'] . ",\"f\":null}]},"; // <-- add comma
}