[英]How can I create a json file from mysql database?
I want to create a json file. 我想创建一个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);
My result: 我的结果:
[{
"id": "123",
"timestamp": "2017-05-12 16:22:39",
"name": "bear",
"description": "dance all day"
},
....
}]
But the format I acutally would need is: 但是我实际需要的格式是:
{
"data": [
[
"123",
"2017-05-12 16:22:39",
"bear",
"dance all day"
],
....
]
}
You can do something like this: 您可以执行以下操作:
$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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.