2017-10-05 157 views
0

我想創建一個json文件。如何從mysql數據庫創建json文件?

$data = $db->query('SELECT * FROM data ORDER BY id ASC;')->fetchAll(PDO::FETCH_ASSOC); 
$json_string = json_encode($data); 
$file = 'data.json'; 
file_put_contents($file, $json_string); 

我的結果:

[{ 
    "id": "123", 
    "timestamp": "2017-05-12 16:22:39", 
    "name": "bear", 
    "description": "dance all day" 
    }, 
    .... 
}] 

但我實際上可以將需要的格式是:

{ 
    "data": [ 
    [ 
     "123", 
     "2017-05-12 16:22:39", 
     "bear", 
     "dance all day" 
    ], 
    .... 
    ] 
} 
+0

您的結果不有一個關閉「]」? – user1506104

+0

更新爲你 – Jarla

+0

這取決於你需要什麼。你需要一個對象數組嗎?或者你需要一個包含數組數據的對象嗎?你的結果是對象數組。你實際需要的格式是後者。兩種有效的json格式。 http://json.org/ – user1506104

回答

1

你可以做這樣的事情:

$results= $db->query('SELECT * FROM data ORDER BY id ASC;')->fetch_all(); 

$data = array(); 
foreach ($results as $row) { 
    $id = $row[0]; 
    $timestamp = $row[1]; 
    $name = $row[2]; 
    $description = $row[3]; 
    $data[] = array($id, $timestamp, $name, $description); 
} 
$json = json_encode(array("data" => $data)); 
+1

更多代碼即將到來 – user1506104

+0

你需要一個json格式的多維數組嗎?等一下。 – user1506104

+0

你怎麼看JSON_PRETTY_PRINT – Jarla