转换对象数组
Convert Array of Objects
我正在尝试将我的邮政编码和城镇转换为 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);
您需要将对象中的每个条目都设为一个数组。这应该有效:
while($row=mysqli_fetch_array($result)){
$matches[] = array(
'label'=> $row["postcode"],
'value'=> $row["town"],
);
}
不要尝试用字符串插入 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);
我正在尝试将我的邮政编码和城镇转换为 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);
您需要将对象中的每个条目都设为一个数组。这应该有效:
while($row=mysqli_fetch_array($result)){
$matches[] = array(
'label'=> $row["postcode"],
'value'=> $row["town"],
);
}
不要尝试用字符串插入 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);