Lewer Smith Lewer Smith - 1 year ago 56
JSON Question

how to retrieve value only of JSON by php from database?

may I know how to retrieve the value only array in json instead of the whole json object in php from the database?

$sql = "SELECT RestaurantName FROM Restaurant";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$restaurantArray = array();
while($rows = mysqli_fetch_assoc($result)) {
$restaurantArray[] = $rows;
echo json_encode($restaurantArray);

For example,

["Afonso Cláudio", "Água Doce do Norte"]

instead of

[{"city":"Afonso Cláudio"},{"city":"Água Doce do Norte"}]

Answer Source

When fetching data from the database as assoc, you will get an associative array (which when converted to json will become a json object) as result.
What you are currently doing is adding the row (which is an associative array with one key-value) to your result array. If you only want the city, you can easily fetch only that data from the assoc-array.

$restaurantArray[] = $rows;


$resturantArray[] = $rows['city'];

should do the trick.

Additionally, if you wanted to reformat the data in the result, and not just push the city name to it, a array_map call could be used:

$result = array_map(function($assocArr) { 
    return $assocArr['city']; // Or whatever you want the value to be.

echo json_encode($result);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download