2013-07-22 199 views
0

我想讓Devbridge Autocomplete jQuery腳本正常工作,而且我非常接近。我可以讓它給我建議(下拉值),但是我需要使用它的數據屬性。以PHP格式化JSON輸出MYSQL

建議的JSON格式爲如下:

{ 
    suggestions: [ 
     { value: "United Arab Emirates", data: "AE" }, 
     { value: "United Kingdom",  data: "UK" }, 
     { value: "United States",  data: "US" } 
] 
} 

到目前爲止,我已設法這樣的:

{ 
"suggestions": [ 
    "Show Name 1", 
    "Show Name 2" 
], 
"data": [ 
    "1", 
    "2" 
] 
} 

生產的是輸出的代碼如下:

$reply = array(); 
$reply['suggestions'] = array(); 
$reply['data'] = array(); 

while ($row = $result->fetch_array(MYSQLI_ASSOC))//loop through the retrieved values 
{ 
    //Add this row to the reply 
    $reply['suggestions'][]=$row['SHOW_NAME']; 
    $reply['data'][]=$row['SHOW_ID']; 
} 

//format the array into json data 
echo json_encode($reply); 

有什麼建議麼?我無法弄清楚如何將兩個數據元素組合成一個陣列,更不用說前面加上他們與「價值」或「數據」 ......

+0

看看這個問題:http://stackoverflow.com/questions/6054033/pretty-printing-json-with-php –

回答

1
while($row = $result->fetch_array(MYSQLI_ASSOC)) 
{ 

$rec = array(); 

$rec['value'] = $row['SHOW_NAME']; 
$rec['data'] = $row['SHOW_ID']; 

$payload['suggestions'][] = $rec; 

} 

echo json_encode($payload); 
+0

' $ payload'永遠不會初始化,並會導致PHP警告。此外,在將變量返回給Javascript函數以改進調試時,建議使用'JSON_PRETTY_PRINT'。 – DevlshOne

1
$response = array(); 
$reply = array(); 
while ($row = $result->fetch_array(MYSQLI_NUM))//loop through the retrieved values 
{ 
    //Add this row to the reply 
    $reply['value'] = $row[0]; 
    $reply['data'] = $row[1]; 
    $response['suggestions'][] = $reply; 
} 
//format the array into json data 
echo json_encode($response, JSON_PRETTY_PRINT); 
0

不知道如果我有你正確但如果你的意思是讓在一個陣列中的兩個值,則使用:

$replay[][array('country' => $row['SHOW_NAME'],'data' => $row['SHOW_ID'])];