这里是我的代码:
<?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);
}
?>,在这之后,我得到了这个格式的响应,
{“错误”:“错误”:“service_name”}{“错误”}{“错误”:“service_name”:“米歇尔沙龙”}{“错误”:假,“service_name”:“米歇尔沙龙”}{错误“错误”:“service_name”:“迈克沙龙”}{“错误”}{“错误”:假,"service_name":"Etta沙龙“}
,我只想让这个响应像这个
{“错误”:“假”,“service_name”:“迈克沙龙”},{“错误”:假,“service_name”:“米歇尔沙龙”},{“错误”:假,“service_name”:“米歇尔沙龙”},{“错误”:假,"service_name":"Mike“},{”错误“:false,”service_name“:”service_name“
请帮助我为json找一份合适的回复表格。谢谢
发布于 2017-03-20 20:17:35
您正在尝试对单个结果进行编码,尝试创建一个数组将所有的结果都编码出来,并将其编码到循环的外面。
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 );发布于 2017-03-20 20:16:36
不要对单个结果进行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);https://stackoverflow.com/questions/42913054
复制相似问题