我是PHP新手。我正在尝试格式化JSON。这是相关代码:
$query = mysql_query("SELECT *
FROM `micards` m
JOIN user u ON m.`mobile` = u.phone");
while ($row = mysql_fetch_assoc($query)) {
$response["success"] = 1;
$name = array('name'=>$row["name"],'email'=>$row["email"],'mobile'=>$row["mobile"]);
$phone[] = array('phone'=>$row["phone"],array('card'=>$name));
$response["contacts"] = $phone;
}
echo json_encode($response);
我得到这个输出:
{
"success": 1,
"contacts": [{
"phone": "919898989898",
"0": {
"card": {
"name": "abcd",
"email": "vwxy@test.com",
"mobile": "919898989898"
}
}
}, {
"phone": "919898989898",
"0": {
"card": {
"name": "abcd",
"email": "rstp@test.com",
"mobile": "919898989898"
}
}
}, {
"phone": "8686868686",
"0": {
"card": {
"name": "pan",
"email": "pnqr@gmail.com",
"mobile": "8686868686"
}
}
}, {
"phone": "8686868686",
"0": {
"card": {
"name": "monk",
"email": "abcd@gmail.com",
"mobile": "8686868686"
}
}
}]
}
但我希望它是:
{
"success": 1,
"contacts": [{
"phone": "919898989898",
{
"card": {
"name": "abcd",
"email": "vwxy@test.com",
"mobile": "919898989898"
}
},
{
"card": {
"name": "abcd",
"email": "rstp@test.com",
"mobile": "919898989898"
}
}
}],
[{
"phone": "8686868686",
{
"card": {
"name": "panky",
"email": "pnqr@gmail.com",
"mobile": "8686868686"
}
},
{
"card": {
"name": "panky",
"email": "abcd@gmail.com",
"mobile": "8686868686"
}
}
}]
}
我能做些什么来获得上述输出?
只需更改此部分:
$phone[] = array('phone'=>$row["phone"],array('card'=>$name));
$response["contacts"] = $phone;
至
$response["contacts"][] = array('phone'=>$row["phone"],array('card'=>$name));
只需复制并粘贴此代码
while ($row = mysql_fetch_assoc($query)) {
$response["success"] = 1;
$name = array('name'=>$row["name"],'email'=>$row["email"],'mobile'=>$row["mobile"]);
$response["contacts"][] = array('phone'=>$row["phone"],array('card'=>$name));
}
请更改
$phone[] = array('phone'=>$row["phone"],array('card'=>$name)) to
$phone[] = array('phone'=>$row["phone"],'card'=>$name)
;
我的猜测是关联数组和打包方式有问题。你可以试着这样组织你的响应数组:
$response = [
'success'=>1,
'contacts'=>[
'phone'=>$row['phone'],
'card'=>[
'name'=>$row['name'],
'email'=>$row['email'],
'mobile'=>$row['mobile']
]
]
];
它应该起作用,你没有检查它。