php - 如何从数据库中修复这个 json 编码
问题描述
我正在研究 JSON 数组。我已经这样做了:
[{"id":"12","text":"Technophile 1 (Branch 1)"},{"id":"29","text":"文莱达鲁萨兰国"}{"id":"135" "文本":"输入 (abc)"}]
但根据标准,我希望以这种方式:
{"results":[{"id":"9","text":"Technophile 1 (Branch 1)"},{"id":"22","text":"Entern (abc)"}] }
意思应该{"result":
在这个 json 的开头和}
结尾。
这是我的代码:
$mysqli = new mysqli('localhost', 'root', '', 'select2');
$sql = "SELECT countries.id, countries.title FROM countries
WHERE title LIKE '%".$_GET['term']."%'
LIMIT 10";
$result = $mysqli->query($sql);
$json = [];
while($row = $result->fetch_assoc()){
$json[] = ['id'=>$row['id'], 'text'=>$row['title']];
}
echo json_encode($json);
解决方案
您要做的是将数据添加到数组中。
echo json_encode(['results' => $json]);
推荐阅读
- python - 如何将文件的所有 git 版本保存到磁盘?
- python - 总结一列单词对并检查频率?
- javascript - VS Typescript 找不到本地文件夹
- java - 如何在实例化变量时遍历列表并将值用作标签或分配的名称?
- git - Github尝试上传文件并获取一系列错误
- spring - 在 IBM MQ 中按计划交付消息 - 提前多长时间?
- php - 正则表达式匹配 next 是空格或字符串结尾
- localhost - 自签名根证书仍然无效
- android-studio - 如何将数据从 Raspberry Pi Python 脚本发送到 Android 应用程序
- faster-rcnn - 是否可以在更快的 R-CNN 中使用我自己的 CNN 模型?