2013-06-26 36 views
0

所以,我需要通過php查詢我的數據庫,然後將查詢轉換爲.json文件以使用Google ChartsPHP mySql數據到JSON文件

我如何轉換一個MySQL查詢通過PHP到以.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:這個例子是從谷歌

回答

7

引用您可以使用json_encode功能。

  1. 從分貝取數據,並將其分配給數組
  2. 然後使用json_encode($result_array)。這將產生json結果。 Click here
  3. 使用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); 
+1

,但我想在json_encode($陣列)發送到 – DaftDev

+0

您要保存結果以.json文件的上傳.json文件,對不對? –

+1

exact.get json_encode($ array)的結果並將其發送到.json文件,以便稍後可以在谷歌圖表中輸出 – DaftDev

1

轉換MySQL表到PHP對象使用mysql_fetch_object,然後用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);