2015-12-03 79 views
0

我试图转换我的邮编和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); 
+0

'$ dname_list [] =阵列( '标签'=> $行[ '邮政编码'], '值'=> $行[ '镇']) ;' – AbraCadaver

回答

0

不要尝试插入带有字符串的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); 
0

你需要让你的对象数组中的每个条目。这应该工作:

while($row=mysqli_fetch_array($result)){ 
    $matches[] = array(
       'label'=> $row["postcode"], 
       'value'=> $row["town"], 
        ); 
}