本文介紹了PHP json_encode() 在 while 循環中的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我試圖在獲取數據庫結果的同時在 while 循環中使用 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()
函數將所有用戶放入數組而不是最后一個.我該怎么做?謝謝
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);
?>
這篇關于PHP json_encode() 在 while 循環中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!