0

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);

1 Answer 1

4

You need to get the float representation of that string, try using either floatval or casting it to a float.

floatval

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 :)

Sign up to request clarification or add additional context in comments.

2 Comments

Close. You need 'attributes'=> array('name' => $row["city"]))
Thank you! Now it makes sense. I will use float.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.