问题
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