本文介紹了PHP json_encode() 在 while 循環(huán)中的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我試圖在獲取數(shù)據(jù)庫結(jié)果的同時在 while 循環(huán)中使用 json_encode()
.這是我的代碼:
I am trying to use json_encode()
in a while loop while getting database results. Here is my code:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
while($row = sqlite_fetch_array($results)) {
$data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>
這個輸出是
{"response":"lastUserID lastUser lastXPos lastYPos"}
{"response":"lastUserID lastUser lastXPos lastYPos"}
我希望它是...
{"response":["1 Alex 10 12", "2 Fred 27 59", "3 Tom 47 19"]}
{"response":["1 Alex 10 12", "2 Fred 27 59", "3 Tom 47 19"]}
等
所以我希望 json_encode()
函數(shù)將所有用戶放入數(shù)組而不是最后一個.我該怎么做?謝謝
So I want the json_encode()
function to put ALL users into the array rather than the last one. How would I do this? Thanks
推薦答案
嘗試:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>
這篇關(guān)于PHP json_encode() 在 while 循環(huán)中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!