[英]MySQL, PHP, jSON append data from MySQL into an array in PHP and converting in jSON file
[英]PHP mySql data to JSON file
因此,我需要通過php查詢數據庫,然后將查詢轉換為.json文件以使用Google圖表 。
我如何通過PHP將mysql查詢轉換為.json文件,如下所示:
{
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:此示例引自Google
您可以使用json_encode
函數。
json_encode($result_array)
。 這將產生json結果。 點擊這里 file_put_contents
函數將json結果保存到您的.json文件中 以下是示例代碼,
$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);
使用mysql_fetch_object將mysql表轉換為php對象,然后使用json_encode轉換為json
mysql_fetch_object獲取行。 因此,請使用循環來構造表對象。
碼:
$result = mysql_query("select * from mytable");
$table=array();
while($row=$mysql_fetch_object($result)){
$table.push($row);
unset($row);
}
echo json_encode($table);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.