问题
So, i need to query my database by php and then convert the query into a .json file to use Google Charts.
How can i convert a mysql query through PHP to a .json file somewhat like this:
{
cols: [{id: 'A', label: 'NEW A', type: 'string'},
{id: 'B', label: 'B-label', type: 'number'},
{id: 'C', label: 'C-label', type: 'date'}
],
rows: [{c:[{v: 'a'}, {v: 1.0, f: 'One'}, {v: new Date(2008, 1, 28, 0, 31, 26), f: '2/28/08 12:31 AM'}]},
{c:[{v: 'b'}, {v: 2.0, f: 'Two'}, {v: new Date(2008, 2, 30, 0, 31, 26), f: '3/30/08 12:31 AM'}]},
{c:[{v: 'c'}, {v: 3.0, f: 'Three'}, {v: new Date(2008, 3, 30, 0, 31, 26), f: '4/30/08 12:31 AM'}]}
],
p: {foo: 'hello', bar: 'world!'}
}
PS: this example is quoted from google
回答1:
You can use json_encode
function.
- Fetch data from db and assign it to an array
- Then use
json_encode($result_array)
. This will produce the json result. Click here - Use
file_put_contents
function to save the json result to your .json file
Following is an example code,
$result = mysql_query(your sql here);
$data = array();
while ($row = mysql_fetch_assoc($result)) {
// Generate the output in desired format
$data = array(
'cols' => ....
'rows' => ....
'p' => ...
);
}
$json_data = json_encode($data);
file_put_contents('your_json_file.json', $json_data);
回答2:
convert mysql table to php object using mysql_fetch_object and then to json with json_encode
mysql_fetch_object fetches row. so use loop to construct a table object.
code:
$result = mysql_query("select * from mytable");
$table=array();
while($row=$mysql_fetch_object($result)){
$table.push($row);
unset($row);
}
echo json_encode($table);
来源:https://stackoverflow.com/questions/17317519/php-mysql-data-to-json-file