$query = "SELECT * from tblTwigUsers;";
$result = mysqli_query ($con,$query);
if (mysqli_num_rows($result)>0)
{
$response = array();
$code = "profile_true";
while($row = mysqli_fetch_array($result))
{
array_push ($response,array("code"=>$code,"fldUser_Id"=>$row[0],"fldUser_UserName"=>$row[2]));
echo json_encode(array("server_resposnse"=>$response));
}
}
else
{
$response = array();
$code = "profile_false";
$message = "failed to get user profile info...";
array_push ($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_resposnse"=>$response));
}
结果
{
"server_resposnse": [{
"code": "profile_true",
"fldUser_Id": "1",
"fldUser_UserName": "sohan"
}]
} {
"server_resposnse": [{
"code": "profile_true",
"fldUser_Id": "1",
"fldUser_UserName": "sohan"
}, {
"code": "profile_true",
"fldUser_Id": "2",
"fldUser_UserName": "sonal"
}]
} {
"server_resposnse": [{
"code": "profile_true",
"fldUser_Id": "1",
"fldUser_UserName": "sohan"
}, {
"code": "profile_true",
"fldUser_Id": "2",
"fldUser_UserName": "sonal"
}, {
"code": "profile_true",
"fldUser_Id": "3",
"fldUser_UserName": "amit"
}]
} {
"server_resposnse": [{
"code": "profile_true",
"fldUser_Id": "1",
"fldUser_UserName": "sohan"
}, {
"code": "profile_true",
"fldUser_Id": "2",
"fldUser_UserName": "sonal"
}, {
"code": "profile_true",
"fldUser_Id": "3",
"fldUser_UserName": "amit"
}, {
"code": "profile_true",
"fldUser_Id": "4",
"fldUser_UserName": "rajiv"
}]
}
为什么数据重复? 第四个结果是正确的,我需要吗?怎么弄? 帮助赞赏,
THX, Sohan
答案 0 :(得分:0)
不要在循环中echo json_encode()
,因为那样你会多次打印JSON,每一个都比前一个稍长一些。等到循环完成后。
$response = array();
if (mysqli_num_rows($result)>0)
{
$code = "profile_true";
while($row = mysqli_fetch_array($result))
{
array_push($response,array("code"=>$code,"fldUser_Id"=>$row[0],"fldUser_UserName"=>$row[2]));
}
}
else
{
$code = "profile_false";
$message = "failed to get user profile info...";
array_push($response,array("code"=>$code,"message"=>$message));
}
echo json_encode(array("server_resposnse"=>$response));
顺便说一下,你拼错了#34;回复"在"server_responsnse"
。确保在此处以及处理JSON的代码中使用相同的拼写。
此外,array_push($array, $value);
可以更加惯用地编写为$array[] = $value;