我想选择数据库更多的值(我已经这样做了)并转换为JSON
我尽力了
php
$a = $_GET['name'];
header('Content-Type: application/json');
echo '{"results":[';
$selectSearch = "SELECT * from `users` WHERE `name` LIKE '".$a["term"]."%'";
$rezultatul = $db->query($selectSearch);
if ($rezultatul->num_rows > 0) {
while($row = $rezultatul->fetch_assoc()) {
$name = $row["name"];
$arr = array('id' => $row["id"], 'text' => $row["name"], 'level' => $row["Level"]);
echo json_encode($arr);
}
}
echo ']}';
他看起来像这样:
{"results":[{"id":"1","text":"Pompiliu","level":"7"}
{"id":"11","text":"Pompiliu1","level":"100"}]}
但是两者之间一定是这样
{"id":"1","text":"Pompiliu","level":"7"},
{"id":"11","text":"Pompiliu1","level":"100"}
什么时候会有3个结果
{"id":"1","text":"Pompiliu","level":"7"},
{"id":"11","text":"Pompiliu1","level":"100"},
{"id":"12","text":"Pompiliu2","level":"100"}
答案 0 :(得分:2)
使用[]
然后使用json_encode添加到数组。
不要尝试自己构建json字符串。
if ($rezultatul->num_rows > 0) {
while($row = $rezultatul->fetch_assoc()) {
$name = $row["name"];
$arr[] = array('id' => $row["id"], 'text' => $row["name"], 'level' => $row["Level"]);
}
}
echo json_encode(["results" => $arr]);