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 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划