I am trying to get a JSON array form PHP output which fetches multiple values from the database and converts to JSON array. The PHP code is as follows:
php
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
//defined second array for dbnames' list
$dblist = array();
while($row = $result->fetch_assoc()){
//array_push($response['dblist'],$row['dbname']);
$dblist = array('name'=>$row['dbname']);
}
$response['dblist'] = $dblist;
echo json_encode($response);
It gives the following output:
JSON
{"dblist":["a","arsod"]}
But, in order to extract values from JSON, the needed array is like:
json
{"dblist":{"name":"a","name":"arsod"}}
how can I achieve this? I want to fetch these values in android app.
Try this:
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
$dblist = [];
while($row = $result->fetch_assoc()){
$dblist[] = ['name'=>$row['dbname']];
}
$response['dblist'] = $dblist;
echo json_encode($reposne);
I basicaly added [] to $dbList so it looks like $dbList[] = ...
And with this, you will get a valid JSON that looks like this:
{"dblist":[{"name":"a"},{"name":"b"}]}
AS you requested output is not a good idea, since you will have duplicate keys in JSON
Your error is a common mistake and basically only effects this row:
$dblist = array('name'=>$row['dbname']);
where you set $dblist
to a new created array in each iteration. What you want to do is adding a new entry to a list on every iteration
$entry = array('name'=>$row['dbname']);
array_push($dblist, $entry);
Which is the same, as
$entry[] = array('name'=>$row['dbname']);