I am currently using a third party api. I am having some diffulties formatting my db values into json objects. The api takes the values on if they’re in a certain format. In the php code below I am using foreach loop to fetch the results. Then array_push
to place the values inside the array. I am getting string data instead of numerical for coordinates
. In the end, I am not getting the desired result. How can I format the json objects to look like the example below?
Current Result:
{
coordinates: [
"-121.2808, 38.3320"
],
attributes: "Sacramento"
},
Desired Result:
{
coordinates: [-121.2808, 38.3320],
attributes: {
name: 'Sacramento'
}
},
PHP loop and json_encode
header("Content-type: application/json");
//get the course list
$location_query = $db_con->prepare("SELECT city, X(location) as latitude, Y(location) as longitude
FROM company
");
$location_query->execute();
$data = $location_query->fetchAll();
$output = array();
foreach ($data as $row) {
array_push($output, array('coordinates'=>array($row["latitude"].",".$row["longitude"]), 'attributes'=>$row["city"]));
}// foreach ($data as $row) {
echo json_encode($output);