0

I've a MySQL database containing GPS coordinates. This is my partial PHP code to retrieve the coordinates;

$sql = "SELECT lat, lon FROM gps_data";
$stmt=$db->query($sql); 
$result=$stmt->fetchAll();

Now i need to 'convert' the returned PHP array to an array of arrays in javascript. I've already tried this;

var js_var = <?php echo json_encode($result); ?>;

But it's not the desired output

Current Output:

var js_var = [{"lat":"61.883350","0":"61.883350","lon":"8.551115","1":"8.551115"},{"lat":"61.883380","0":"61.883350","lon":"8.551715","1":"8.551715"}];

Desired output:

var js_var =
[[61.883350,8.551115],[61.883380,8.551715]];

how to achieve this ?

1
  • Print your array then only we will assist? Commented Apr 7, 2015 at 6:26

2 Answers 2

5

You can use .map, like so

var js_var = [{"lat":"61.883350","0":"61.883350","lon":"8.551115","1":"8.551115"},{"lat":"61.883380","0":"61.883350","lon":"8.551715","1":"8.551715"}];

var result = js_var.map(function (el) {
  return [el.lat, el.lon];
});

console.log(result);

0
0

Try

$sql = "SELECT lat, lon FROM gps_data";
$stmt=$db->query($sql); 
$result=$stmt->fetchAll();
$final=array();
foreach($result as $row) {
    $final[]=array($row[0],$row[1]);
}

And

var js_var = <?php echo json_encode($final); ?>;
1
  • Now it outputs as OP needs, i have formed new array as per as his needs Commented Apr 7, 2015 at 6:41

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.