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);
You need to get the float representation of that string, try using either floatval
or casting it to a float.
floatval($row["latitude"])
Casting
(float) $row["latitude"]
Do this for both latitude and longitude.
Also for some reason you are building a string with a comma in it. To produce the proper representation it should look like this.
array_push($output, array(
'coordinates' => array((float) $row["latitude"], (float) $row["longitude"]),
'attributes' => array('name' => $row["city"]))
));
Arrays with keys represent objects, hence the array with a key => value.
Edit : Thanks to Mike for pointing out the attribute error, was too focused on the casting :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.