1

The form I require is:

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

What I get with this php code:

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);

is this:

{"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"}]]}

That extra [ is causing a problem since it's not in the format I need. How can I do this correctly?

3
  • Here's a solution that other user posted: stackoverflow.com/questions/15678355/… Commented Aug 2, 2017 at 10:49
  • @guillefix — That's for hacking around the problem when the JSON is parsed (assuming it is being parsed in JS). The question is asking about fixing the data at source. Commented Aug 2, 2017 at 10:50
  • MedicineName !== value and MedicineID !==data Commented Aug 2, 2017 at 10:51

2 Answers 2

6

This:

$reply['suggestions'][]=$res;
  1. Gets $reply['suggestions']
  2. Assigns an empty array to if it one doesn't already exist there
  3. Puts $res (already an array) as the next item in that array

You just want to put $res as the value of $reply['suggestions'].

Remove the [].

$reply['suggestions']=$res;
Sign up to request clarification or add additional context in comments.

Comments

2

Try changing $reply['suggestions'][]=$res; to $reply['suggestions']=$res;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.