我需要的形式是:創建某些JSON形式
{
"suggestions": [
{ "value": "United Arab Emirates", "data": "AE" },
{ "value": "United Kingdom", "data": "UK" },
{ "value": "United States", "data": "US" }
]
}
我得到了這個PHP代碼:
header("Content-type: application/json");
require 'connect.inc.php';
$mysql = mysqli_connect("$db_host", "$db_username", "$db_pass", "$db_name");
$name = isset($_POST['query']) ? $_POST['query'] : "";
$sql = "SELECT MedicineName, MedicineID FROM medicinetypes WHERE MedicineName LIKE '%$name%'";
$res = mysqli_query($mysql, $sql);
$res = mysqli_fetch_all($res, MYSQLI_ASSOC);
$reply = array();
$reply['suggestions'][]=$res;
echo json_encode($reply);
mysqli_close($mysql);
是這樣的:
{"suggestions":[[{"MedicineName":"Amoxil 500","MedicineID":"1"},{"MedicineName":"Panadol","MedicineID":"2"},{"MedicineName":"Farmako3","MedicineID":"3"},{"MedicineName":"Beer","MedicineID":"4"},{"MedicineName":"Farmako4","MedicineID":"5"},{"MedicineName":"hjkki","MedicineID":"61"},{"MedicineName":"Amoxil 1","MedicineID":"577"},{"MedicineName":"Amoxil 502","MedicineID":"580"},{"MedicineName":"Amoxil 56","MedicineID":"582"},{"MedicineName":"Amoxil 600","MedicineID":"583"},{"MedicineName":"\u03b5\u03bb\u03b1 \u03bc\u03bf\u03c5 \u03bd\u03c4\u03b5","MedicineID":"586"}]]}
由於它不符合我需要的格式,因此導致了一個問題。我怎樣才能正確地做到這一點?
下面是其他用戶發佈的解決方案: https://stackoverflow.com/questions/15678355/remove-extra-square-bracket-from-json – guillefix
@guillefix - 這是爲了解決JSON解析時的問題(假設它在JS中被解析)。問題在於詢問如何在源頭修復數據。 – Quentin
'MedicineName!==值'和'MedicineID!==數據' –