Lewer Smith Lewer Smith - 1 month ago 6
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?

<?php
require_once('dbConnect.php');
$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);
mysqli_close($connection);
?>


For example,

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


instead of

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

Answer

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

$restaurantArray[] = $rows;

to

$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.
}, 
$resturantArray);

echo json_encode($result);