0

Trying to fetch the latlng from database and encode to Json but I got only 1 result.

 $geo= new stdClass();

 while( $rows = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
            $name=$rows['Name'];
            $lat=$rows['Latitude'];
          $lng=$rows['Longitude'];
            $intlat=(float)$lat;
            $intlng=(float)$lng;
            $latlng = $lat.",".$lng;
            $geo->lat=$intlat;
            $geo->lng=$intlng;

}


 $try1=json_encode(array("location"=>$geo));
 echo $try1;

Result {"location":{"lat":13.811,"lng":100.612}}

But what I want is {"location":{"lat":13.811,"lng":100.612},{"lat":v2,"lng":v2},{"lat":v3,"lng":v3},{"lat":v4,"lng":v4}}

3
  • 2
    In this loop you are overwriting your values... so at the end you have only 1 result Commented Apr 18, 2018 at 15:26
  • @B001ᛦ So what should I change ? Commented Apr 18, 2018 at 15:31
  • 1
    Note that your wanted JSON is invalid. I think you want something like: {"location":[{"lat":13.811,"lng":100.612},{"lat":13.811,"lng":100.612}]} Commented Apr 18, 2018 at 15:41

2 Answers 2

2

If you want to add multiple locations, you should initialize an array to hold them, rather than a stdClass object. If you're concerned about the result ending up as an object rather than an array in the resulting JSON, it will be okay. If an array has string keys (like the inner arrays will) it will be encoded as an object in the JSON.

$geo = [];

Then as you fetch rows, append them to the array after doing whatever transformations you need to do.

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {
    $geo[] = ['lat' => (float) $row['Latitude'], 'lng' => (float) $row['Longitude']];
}

echo json_encode(["location" => $geo]);
Sign up to request clarification or add additional context in comments.

Comments

2

You don't build an object or array in the loop. It is much simpler if in your query you just SELECT Latitude AS lat, Longitude as lng ...

while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    $geo[] = array_map('floatval', $row);
}
echo json_encode(array('location' => $geo));

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.