这是我的代码:
<?php
while ($row = mysqli_fetch_assoc($searching_user))
{
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response["error"] = FALSE;
$response["service_name"] = $salon_name;
echo json_encode($response);
}
?>
在此之后我收到了这种格式的回复
{ “错误”:假, “服务名”:“麦克 沙龙“} {”错误“:false,”service_name“:”米歇尔沙龙“} {“error”:false,“service_name”:“Michel salon”} {“error”:false,“service_name”:“Mike Salon”} {“error”:false,“service_name”:“Etta Salon”}
我只想要这样的回复
[{“error”:false,“service_name”:“迈克 沙龙 “},{” 错误 “:假,” 服务名 “:” 米歇尔 沙龙 “},{” 错误 “:假,” 服务名 “:” 米歇尔 salon“},{”error“:false,”service_name“:”Mike Salon“}, {“error”:false,“service_name”:“Etta Salon”}]
请帮助我为json获取一份正确的回复表格。 感谢
答案 0 :(得分:1)
不要json_encode()单个结果,而是把它们放到一个数组中,最后json_encode()表示:
<?php
$response = [];
while ($row=mysqli_fetch_assoc($searching_user)) {
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response[] = [
'error' => FALSE,
'service_name' => $salon_name,
// you may want to add more attributes here...
];
}
echo json_encode($response);
我个人建议缩短这一点:
<?php
$response = [];
while ($row=mysqli_fetch_assoc($searching_user)) {
$response[] = [
'error' => FALSE,
'service_name' => ucfirst($row['service_name']),
'salon_id' => $row['id'],
'salon_address' => ucwords($row['address']),
'salon_area' => ucwords($row['area']),
'salon_city' => ucwords($row['city']),
'salon_specialty' => ucwords($row['specialty']),
'img' => $row['image_url'],
];
}
echo json_encode($response);
答案 1 :(得分:0)
您正在尝试对单个结果进行编码,尝试创建一个数组将所有结果并将其编码到循环旁边。
while ($row=mysqli_fetch_assoc($searching_user)) {
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response["error"] = FALSE;
$response["service_name"]=$salon_name;
// Added this line
$responses[] = $response;
}
//Encode all results
echo json_encode($responses );