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 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输