如何使用PHP将这些数据格式化为json,以便谷歌图表可以理解它?

时间:2015-07-07 07:15:08

标签: php json sqlite

$result = $db->query($select_msgsum); //query the new msgsum table

    //defining label that google needs  
      $col1 = array();
      $col1["id"]="";
      $col1["label"]="MessageType";
      $Col1["pattern"]="";
      $col1["type"]="string";

      $col2 = array();
      $col2["id"]="";
      $col2["label"]="MessageCount";
      $Col2["pattern"]="";
      $col2["type"]="number";

    // rows?  

    //filling the json data to it
    while($data=$result->fetchArray()){
       array_push($col1, $data['msg_type']);
       array_push($col2, $data['msg_count']);
    }
    $cols = array($col1, $col2);
    file_put_contents('../json/chart_data.json', json_encode($cols));
  ?>

我得到的结果如下所示,不接受如下所述:https://developers.google.com/chart/interactive/docs/php_example

[
    {
        "0": "General question",
        "1": "Job-fulltime",
        "2": "Job-parttime",
        "3": "Just Hello",
        "id": "",
        "label": "MessageType",
        "type": "string"
    },
    {
        "0": 6,
        "1": 3,
        "2": 9,
        "3": 12,
        "id": "",
        "label": "MessageCount",
        "type": "number"
    }
]

1 个答案:

答案 0 :(得分:1)

你可以直接将查询结果转换为JSON ..试试这个..

    $result = $db->query($select_msgsum);
    $rows = array();
    while($r = mysqli_fetch_assoc($result)) {
        $rows[] = $r;
    }
    print json_encode($rows);