duanjiao7440 2015-07-07 07:15
浏览 66
已采纳

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

$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));
  ?>

The result i get is as following which is not accepted as explained here: 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条回答 默认 最新

  • duannian7116 2015-07-07 07:21
    关注

    you can directly convert the result from query to JSON.. try this ..

        $result = $db->query($select_msgsum);
        $rows = array();
        while($r = mysqli_fetch_assoc($result)) {
            $rows[] = $r;
        }
        print json_encode($rows);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入