【问题标题】:How to fix this json encode from database如何从数据库中修复此 json 编码
【发布时间】:2019-09-10 21:34:45
【问题描述】:

我正在处理 JSON 数组。我已经这样做了:

[{"id":"12","text":"Technophile 1 (Branch 1)"},{"id":"29","text":"文莱达鲁萨兰国"}{"id": "135","text":"Entern (abc)"}]

但根据标准,我希望这样:

{"results":[{"id":"9","text":"Technophile 1 (Branch 1)"},{"id":"22","text":"Entern (abc) "}]}

意思是这个json的开头应该有{"result":,结尾应该有}

这是我的代码:

$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(array("results"=>$json))?

标签: php arrays json xcode


【解决方案1】:

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

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

【讨论】:

  • 这个答案还可以,但是你可以通过添加json_encode命令的链接来改进它,并解释PHP数组和json对象之间的联系
猜你喜欢
  • 1970-01-01
  • 2018-08-21
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
相关资源
最近更新 更多