I wish to prepare the JSON data and send to jquery autocomplete made by devbridge, it want the data be format as this scheme:
{
"suggestions": [
{ "value": "United Arab Emirates", "data": "AE" },
{ "value": "United Kingdom", "data": "UK" },
{ "value": "United States", "data": "US" }
]
}
So I'm trying to get the data from database and put in an array.
<?php
include '../core/config.php';
include '../core/db.class.php';
$DB->query("SELECT * FROM `prodotti`;");
$prodotti = $DB->fetchAll();
class json_prodotti {
public $suggestions = '';
}
class json_suggestions {
public $value = '';
public $data = '';
public $price = '';
}
$j = new json_prodotti;
$s = new json_suggestions;
$a = array();
foreach ($prodotti as $prd ) {
$s->value = $prd['name'];
$s->data = $prd['ID'];
$s->price = $prd['price'];
array_push($a,$s);
}
$j->suggestions = $a;
echo json_encode($j);
?>
As you can see I'm using a database class, this work as expected and I'm using it in other parts of project. Here is the function fetchAll() that is called to fetch the data, the __construct is working fine.
public function fetchAll(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
PROBLEM:
Something is wrong in my code, I got the JSON as expected, but the foreach cycle repeat the same database row as many rows I got in database. EG:
{
"suggestions":[
{"value":"Item 4","data":"6","price":"0.48"},
{"value":"Item 4","data":"6","price":"0.48"},
{"value":"Item 4","data":"6","price":"0.48"},
{"value":"Item 4","data":"6","price":"0.48"}
]}