Reputation: 2749
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
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
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
Reputation: 522175
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
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