John Doe
John Doe

Reputation: 10183

php array (of arrays) to javascript

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 ?

Upvotes: 0

Views: 57

Answers (2)

Sagar Devkota
Sagar Devkota

Reputation: 1192

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

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77482

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

Upvotes: 5

Related Questions