2015-12-03 122 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"], 
        ); 
}