在将数据编码为JSON时,如何将数据构建为所需格式?

时间:2014-06-17 10:27:22

标签: php google-visualization json

我正在开发一个需要谷歌图表来显示MySql数据库结果的应用程序。在将数据编码为JSON时,如何将数据构建为所需格式?

到目前为止,这是我的代码:

$con=mysql_connect("localhost","root","") or die("Failed to connect with database!!!!");
mysql_select_db("su_data", $con);

$result = mysql_query("SELECT * FROM chart");    
$data = array();
while ($row = mysql_fetch_object($result)) {
// Generate the output in desired format
$data[]=$row;
}

我希望它看起来像这样:

{
  "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}]}
      ]
}

2 个答案:

答案 0 :(得分:0)

我不知道在PHP中,但在Java Web应用程序中,我们在控制器上使用Gson(谷歌库),在视图级别,我们使用了jersey库将对象转换为JSON

答案 1 :(得分:0)

$result = mysql_query("SELECT * FROM chart");    
    $data = array();
    $cols[]=array('label'=>"Month",'type'=>'string');
    $cols[]=array('label'=>"Actual 2013",'type'=>'number');
    $cols[]=array('label'=>"Actual 2014",'type'=>'number');
    $cols[]=array('label'=>"Forecast 2014",'type'=>'number');       


    while ($row_result = mysql_fetch_assoc($result)) {

        $c[] = array('v'=>$row_result['month'], 'f'=>null);
        $c[] = array('v'=>$row_result['actual_2013'], 'f'=>null);
        $c[] = array('v'=>$row_result['actual_2014'], 'f'=>null);
        $c[] = array('v'=>$row_result['forecast_2014'], 'f'=>null);

        $rows[]=array('c'=>$c);


         $data = array(
         'cols' => $cols,
         'rows' => $rows);
         unset($c);}



   // echo '<pre>';
//      print_r($data);

    $json_data = json_encode($data);
    //echo '<pre>';
//        echo $json_data;
    file_put_contents('sample.json', $json_data);