我想在获取数据库结果的同时在while循环中使用json_encode()
。这是我的代码:
<?
$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”}
我希望它是......
{“回应”:[“1 Alex 10 12”,“2 Fred 27 59”,“3 Tom 47 19”}}
等
所以我希望json_encode()
函数将所有用户放入数组而不是最后一个。我该怎么做?感谢
答案 0 :(得分:4)
尝试:
<?
$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);
?>
答案 1 :(得分:3)
更改此
while($row = sqlite_fetch_array($results)) {
$data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
到
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
答案 2 :(得分:2)
将每个用户推送到一个数组:
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));