dongzan0108 2017-01-25 00:59 采纳率: 0%
浏览 51
已采纳

PHP:从数据库为JS自动完成创建JSON数据

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"}
]}
  • 写回答

1条回答 默认 最新

  • dslfq06464 2017-01-25 01:47
    关注

    Just create a new suggestion each time:

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

    Otherwise you are modifying the same object... thats why in json_encode you get the same value for all suggestions... you are adding the same suggestion many times...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备