[英]I need help in json response in php
这是我的代码:
<?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”:“迈克沙龙”} {“错误”:false,“ service_name”:“米歇尔沙龙”} {“错误”:错误,“服务名”:“米歇尔沙龙”} {“错误”:false,“ service_name”:“ Mike Salon”} {“错误”:false,“ service_name”:“ Etta Salon”}
我只是想要这样的回应
[{“ error”:false,“ service_name”:“ Mike salon”},{“ error”:false,“ service_name”:“ Michel salon”},{“ error”:false,“ service_name”:“ Michel salon” },{“ error”:false,“ service_name”:“迈克沙龙”},{“ error”:false,“ service_name”:“ Etta Salon”}]
请帮助我为json获取正确的响应表。 谢谢
不要将单个结果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);
您正在尝试对单个结果进行编码,尝试创建一个数组将所有结果并在循环外进行编码。
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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.