jonboy
jonboy

Reputation: 2749

JSON and array structure typeahead

I am trying to create a json file from an sql query, and search this json using twitter typeahead. However the json format doesn't look correct.

The json needs to be in a certain format for typeahead like below;

['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California' ...];

However my json is in the following format;

["{\"title\":\"Item 1\"}","{\"title\":\"Item 2\"}","{\"title\":\"Item 3\"}"

Newbie to php/sql/json I'm sure there is something really obvious I'm missing or doing wrong. Maybe I should be using a foreach and not while? I am able to echo out the $titles so I now the query is working.

If somebody cold point me in the right direction I would appreciate it.

My code so far;

$sql = ("SELECT title FROM publication");

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}

$data = array();

while($row = $result->fetch_assoc()){
    $data[] = json_encode($row);
    $titles = json_encode($data);
    echo $titles;//for testing
}

file_put_contents('titles.json', $titles);

Upvotes: 0

Views: 88

Answers (4)

PHP Worm...
PHP Worm...

Reputation: 4224

Use json_encode once

    $data[] = $row; /*$data[] = json_encode($row);*/

and write this:

 $titles = json_encode($data);  

OR

$titles = json_encode(array_values($data));  /*You may need to use this to get exact output*/

After while loop

Upvotes: 0

Toumash
Toumash

Reputation: 1087

You are inserting associative array to your json array('title'=>'sometitle') but you only need that title.
The solution is to only save the title value from the db resulting row to the array:

while($row = $result->fetch_assoc()){
    $data[] = $row['title'];
    echo json_encode($data); // dont encode twice
}
file_put_contents('titles.json', json_encode($data));

Upvotes: -1

deceze
deceze

Reputation: 522175

  1. You're over-encoding your data and
  2. you're not including the data you actually want.

Put the data you want into the array and JSON-encode the whole thing only at the end:

while ($row = $result->fetch_assoc()) {
    $data[] = $row['title'];
}

file_put_contents('titles.json', json_encode($data));

Upvotes: 1

Ashish Choudhary
Ashish Choudhary

Reputation: 2034

You are performing json_encode twice which should not be the case.

Instead the Code should be like below:

$data[] = $row;
$titles = json_encode($data);

or simply

$titles = json_encode($row);

Upvotes: 1

Related Questions