2017-07-03 72 views
0

嗨,我有名字Users表有這些列解決這個問題:如何使用json_encode(從數據庫PHP數組)導致

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" 
    } 
}} 

回答

3

要麼告訴mysql_fetch_arrayMYSQLI_ASSOC獲取關聯數組:

$user = mysql_fetch_array($result, MYSQLI_ASSOC); 

或使用該mysqli_fetch_assoc獲取關聯數組:

$user = mysqli_fetch_assoc($result); 
2

使用mysqli_fetch_assoc()

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

順便說一下你的代碼似乎有點過。你確定你只想讓這種格式的單個用戶返回嗎?