gpt4 book ai didi

mysql - 如何从 mysql 数据库创建 json 文件?

转载 作者:行者123 更新时间:2023-11-29 10:34:59 24 4
gpt4 key购买 nike

我想创建一个 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"
],
....
]
}

最佳答案

你可以这样做:

$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));

关于mysql - 如何从 mysql 数据库创建 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46583103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com