Encoding string to json

寵の児 提交于 2019-12-25 07:45:21

问题


I' ve got a problem with encoding string to json. I'm doing a google pie chart. Chart will be filled with data from database. Google chart requires data in json format.

Below is the example of a string how it supposed to look like. Now I have a problem with dynamically "assembling" the string with data from database. JSON_encode is not enough, it has to be in format like this string with cols and rows! Please help.

<?php 

 $db=new DB();
 $db->connect();
 $db->selectBase();

 $rows = array();
 $sth=$db->st_glede_na_tip() or die(mysql_error());
 while($r = mysql_fetch_assoc($sth)) {
     $rows[] = $r;
}


 $string= '{
     "cols": [
        {"id":"","label":"Content","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
       ],
    "rows": [
        {"c":[{"v":"Books"},{"v":3}]},
        {"c":[{"v":"Video"},{"v":1}]},
        {"c":[{"v":"Audio"},{"v":1}]},
        {"c":[{"v":"Movie"},{"v":1}]},
      ]
   }';

   echo $string;


 ?>

回答1:


I'm guessing your problem is not knowing how to generate such a JS object from a PHP object. You need to create a PHP array as such and then use the json_encode function :

$data = array(
    'cols' => array(
        array('id' => '', 'label' => 'Content', 'pattern' => '', 'type' => 'string'),
        array('id' => '', 'label' => 'Slices', 'pattern' => '', 'type' => 'number')     
    ),
    'rows' => array(
        array('c' => array(
            array('v' => 'Books'),
            array('v' => 3)         
        )), 
        array('c' => array(
            array('v' => 'Video'),
            array('v' => 1)         
        )),     
        array('c' => array(
            array('v' => 'Audio'),
            array('v' => 1)         
        )),     
        array('c' => array(
            array('v' => 'Movie'),
            array('v' => 1)         
        ))      
    )   
);  

echo json_encode($data);


来源:https://stackoverflow.com/questions/11500366/encoding-string-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!