我正试图在一组JSON对象中转换邮政编码和城镇,但我想我做得不对,我需要它来实现自动完成功能。
这是我的代码:
$sql = "SELECT * FROM uk_postcodes";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
// [ { label: "Choice1", value: "value1" }, { label: "Choice2", value: "value2" } ]
$dname_list[] = "{label:".$row['postcode'].","."value:".$row['town']."}";
}
header('Content-Type: application/json');
echo json_encode($dname_list);
不要试图插入带有字符串的json。您可以完全依赖json_encode。
这就是我做的方式
$sql = "SELECT * FROM uk_postcodes";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$dname_list[] = array(
"label" => $row['postcode'],
"value" => $row['town']
);
}
header('Content-Type: application/json');
echo json_encode($dname_list);
您需要使对象中的每个条目都成为一个数组。这应该有效:
while($row=mysqli_fetch_array($result)){
$matches[] = array(
'label'=> $row["postcode"],
'value'=> $row["town"],
);
}