0

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 Answer 1

1

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...

Sign up to request clarification or add additional context in comments.

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.