0

I am trying to get remote autocomplete array

$items = array(
    "PR-1001"=>"Product 1",
    "PR-1002"=>"Product 2"
);

Input autocomplete suggection will be PR-1001 and PR-1002 and div will be appended with Product 0 or Product 2 depending on selection of autocomplete. I tried using following code but can't Please help me to get array as mentioned above.

$query = "SELECT * FROM products";
$results = mysql_query($query, $connection);
confirm_query($results);
$count = mysql_num_rows($results);
while($row = mysql_fetch_array($results)) {
    $codes =array("{$row['pr_code']}");
    $names =array("{$row['pr_name']}");
        $i = 0;
        $items[$i] = "\"" . $codes[$i] ."\"=>\"" . $names[$i] ."\", ";
        $items = implode(", ", $items);
        $i++;   
    } 

I need a php array that show print_r

Array ( [DJ-1001] => Product 1 [DJ-1002] => Product 2 )

Thank you in advance.


Here's answer

$items = array();
while($row = mysql_fetch_array($results)) { 
  $items[$row['pr_code']] = $row['pr_name'];
}

Thank you friends!

3 Answers 3

1

Without having any idea what your schema looks like:

$items = array();
while($row = mysql_fetch_array($results)) {
    $items[$row['pr_code']] = $row['pr_name'];
}
echo json_encode($items);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Sir, I got this result {"DJ-1001":"Product 1","DJ-1002":"Product 2"} I am trying to get it as $items = array( "PR-1001"=>"Product 1","PR-1002"=>"Product 2");
@Saleem the result you described is the JavaScript equivalent.
1

in PHP you can have associative array where the key can either be an integer or a string. The value can be of any type. given that you can do straight assignement of key=>value from your query and then return the array in json (jquery-ui autocomplete it's modeled around it so just take a snippet from the official documentation to see how it works):

$items = array();
while($row = mysql_fetch_array($result))
    $items[$row['pr_code']] = $row['pr_name'];

echo json_encode($items);

Comments

1

The data from local data, a url or a callback can come in two variants:

• An Array of Strings: [ "Choice1", "Choice2" ]

• An Array of Objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

$arr   = array();
while($row = mysql_fetch_array($results)) { 
    array_push($arr,'{ label: "' . $row['pr_code'] . '", value: "' . $row['pr_name'] . '" }'); 
}

echo "[" . implode(',',$arr) . "]";

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.