简体   繁体   中英

How do I format this data in to json using PHP so google chart could understand it?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM