我想基于MySQL数据创建JSON文件,但是由于某些原因,我的代码根本无法正常工作(我没有任何错误)
$results= $panel->query('SELECT * FROM servers ORDER BY id ASC;')->fetch_all();
$data = array();
foreach ($results as $row) {
$data[] = $row;
}
$json_string = json_encode($data);
$file = 'servers.json';
file_put_contents($file, $json_string);
我想要什么:
{
"ID": [
"IPOFTHESERVERFROMDATABASE",
PORTFROMDATABASE,
"NAMEFROMDATABASE"
],
..
}
我得到的是什么
[["ID","NAME","IP","PORT","RCON"]]
答案 0 :(得分:2)
您没有将任何东西放入$data
数组中。
更改以下代码,以在$data
对其进行行之前将行加载到json_encode()
数组中
$results= $panel->query('SELECT * FROM servers ORDER BY id ASC;')->fetch_all();
$data = array();
foreach ($results as $row) {
$data[] = $row;
}
$json_string = json_encode($data);
$file = 'servers.json';
file_put_contents($file, $json_string);
或者如雷在下面说的那样,因为您使用了fetchAll
,您可能可以不用foreach循环而这样做
$results= $panel->query('SELECT * FROM servers ORDER BY id ASC;')->fetch_all();
$json_string = json_encode($results);
$file = 'servers.json';
file_put_contents($file, $json_string);
您说要
{
"ID": [
"IP",
PORT,
"NAME"
],
"ID": [
"IP",
PORT,
"NAME"
]
}
当然不可能,因为您有两个具有相同名称的键/属性,即"ID"
$results= $panel->query('SELECT * FROM servers ORDER BY id ASC;')->fetch_all();
$data = array();
foreach ($results as $row) {
$data[$row[0]] = [$row[2],$row[3],$row[1]];
}
$json_string = json_encode($data);
$file = 'servers.json';
file_put_contents($file, $json_string);