2017-08-02 67 views
1

我需要的形式是:創建某些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"}]]} 

由於它不符合我需要的格式,因此導致了一個問題。我怎樣才能正確地做到這一點?

+0

下面是其他用戶發佈的解決方案: https://stackoverflow.com/questions/15678355/remove-extra-square-bracket-from-json – guillefix

+0

@guillefix - 這是爲了解決JSON解析時的問題(假設它在JS中被解析)。問題在於詢問如何在源頭修復數據。 – Quentin

+0

'MedicineName!==值'和'MedicineID!==數據' –

回答

6

此:

$reply['suggestions'][]=$res; 
  1. 獲取$reply['suggestions']
  2. 分配一個空數組,如果它一個不存在有
  3. 提出$res(已經陣列)作爲該陣列中的下一項

您只需要將$res設置爲$reply['suggestions']的值即可。

刪除[]

$reply['suggestions']=$res; 
+0

啊我真是太蠢!謝謝 – Constantine

2

嘗試改變$reply['suggestions'][]=$res;$reply['suggestions']=$res;