首页 > 解决方案 > 如何从数据库中修复这个 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);

标签: phparraysjsonxcode

解决方案


您要做的是将数据添加到数组中。

echo json_encode(['results' => $json]);

推荐阅读