将数据库导出到json时,我会以这种形式得到它:
[
{
"id": "1",
"siteId": "1",
"siteUrl": "localhost",
"identity": "mobie",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB",
}
]
警告:第81行的C:\ xamppp \ htdocs \ auth \ mysql.php中的非法字符串偏移'id'
到所有$ user变量。
我的数据库结构如上所示在第一个json输出中显示。
代码
public function db2json($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$data=$stmt->fetch(PDO::FETCH_ASSOC);
$output = [];
foreach ( $data as $result ) { // Change this to loop over the data
$user = [];
$user["id"] = $result["id"];
$user["siteId"] = $result["siteId"];
$user["lastIp"] = $result["lastIp"];
$user["lastLogin"] = $result["lastLogin"];
$user["loginCountry"] = $result["loginCountry"];
$output[$result["siteUrl"]][$result["identity"]] = $user;
}
echo json_encode($output, JSON_PRETTY_PRINT);
}
答案 0 :(得分:1)
我不得不建立一些测试数据,但这只是意味着你改变foreach()
来代替你的数据库结果。而不是直接将结果直接分配给输出,这只是在输出中创建各种数组...
$output = [];
foreach ( $data as $result ) { // Change this to loop over the data
$user = [];
$user["id"] = $result["id"];
$user["siteId"] = $result["siteId"];
$user["lastIp"] = $result["lastIp"];
$user["lastLogin"] = $result["lastLogin"];
$user["loginCountry"] = $result["loginCountry"];
$output[$result["siteUrl"]][$result["identity"]] = $user;
}
echo json_encode($output, JSON_PRETTY_PRINT);
使用我的测试数据,输出......
{
"localhost": {
"mobie": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
},
"user2": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
}
},
"othersite": {
"user1": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
}
}
}