如何使用json_encode(来自数据库的php数组)结果来解决这个问题

时间:2017-07-03 17:32:23

标签: php json mysqli

您好我有一个名为Users的表,其中包含以下列:

UserId INT
DisplayName VARCHAR(50)
Username VARCHAR(50)
Password VARCHAR(50)

我使用mysqli(mysqli_querymysqli_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"
    }
}}

2 个答案:

答案 0 :(得分:3)

告诉mysql_fetch_array使用MYSQLI_ASSOC获取关联数组:

$user = mysql_fetch_array($result, MYSQLI_ASSOC);

或者使用获取关联数组的mysqli_fetch_assoc

$user = mysqli_fetch_assoc($result);

答案 1 :(得分:2)

使用mysqli_fetch_assoc()

$users=array();
while($user=mysqli_fetch_assoc($result)
  $users=array("User"=>$user);
echo json_encode(array("Users"=>$users));

顺便说一下你的代码有点偏。您确定只想让这种格式的用户返回吗?