我希望准备JSON数据并发送到由devbridge生成的jquery自动完成,它希望数据格式为此方案:
{
"suggestions": [
{ "value": "United Arab Emirates", "data": "AE" },
{ "value": "United Kingdom", "data": "UK" },
{ "value": "United States", "data": "US" }
]
}
所以我试图从数据库中获取数据并放入数组。
<?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);
?>
正如您所看到的,我正在使用数据库类,这项工作正如预期的那样,我在项目的其他部分使用它。这是调用fetchAll()函数来获取数据,__ construct正常工作。
public function fetchAll(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
问题:
我的代码出了问题,我按预期获得了JSON,但是foreach循环重复了与数据库中的行数相同的数据库行。 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"}
]}
答案 0 :(得分:1)
每次只需创建一个新建议:
$j = new json_prodotti;
$a = array();
foreach ($prodotti as $prd ) {
$s = new json_suggestions;
$s->value = $prd['name'];
$s->data = $prd['ID'];
$s->price = $prd['price'];
array_push($a,$s);
}
否则你正在修改同一个对象...这就是为什么在json_encode中你得到所有建议的相同值...你多次添加相同的建议......