您好我有一个名为Users
的表,其中包含以下列:
UserId INT
DisplayName VARCHAR(50)
Username VARCHAR(50)
Password VARCHAR(50)
我使用mysqli(mysqli_query
,mysqli_fetch_array
)从此表中获取记录,如下所示:
$users=array();
while($user=mysqli_fetch_array($result)
$users=array("User"=>$user);
echo json_encode(array("Users"=>$users));
,json_encode的结果是:
{"users":{
"user":{
"0":"1",
"UserId":"1",
"1":"name",
"DisplayName":"name",
"2":"usernameTest",
"Username":"usernameTest",
"3":"passwordTest",
"Password":"passwordTest"
}
}}
但必须是:
{"users":{
"user":{
"UserId":"1",
"DisplayName":"name",
"Username":"usernameTest",
"Password":"passwordTest"
}
}}
答案 0 :(得分:3)
告诉mysql_fetch_array
使用MYSQLI_ASSOC
获取关联数组:
$user = mysql_fetch_array($result, MYSQLI_ASSOC);
或者使用获取关联数组的mysqli_fetch_assoc
:
$user = mysqli_fetch_assoc($result);
答案 1 :(得分:2)
$users=array();
while($user=mysqli_fetch_assoc($result)
$users=array("User"=>$user);
echo json_encode(array("Users"=>$users));
顺便说一下你的代码有点偏。您确定只想让这种格式的用户返回吗?