-1

I have this code to fetch all data from database

while($row = mysqli_fetch_array($query)){                          
$therow1 = $row['r1'];
$therow2 = $row['r2'];
$therow3 = $row['r3'];//get
$therow4 = $row['r4'];//get

}

How can I get the $therow3 and $therow3 as an array then pass it on javascript as array.

The expected output in javascript array would be: $the_array

 [
    [-33.890542, 151.274856],
    [-33.923036, 151.259052],
    [-34.028249, 151.157507],
    [-33.80010128657071, 151.28747820854187],
    [-33.950198, 151.259302]
    ];

Then I will use this array in javascript

<script type="text/javascript">
    var locations = $the_array;

</script>
c.k
  • 1,075
  • 1
  • 18
  • 35

2 Answers2

0

To send an array in a format JavaScript understands, you need to encode it as JSON in PHP, then decode it in the Javascript

<?php
    $the_array = json_encode([
        $row['r3'], $row['r4']
    ]);
?>

<script type="text/javascript">
    var locations = JSON.parse('<?=$the_array?>');
</script>
BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
0

Please try this:

PHP:

while($row = mysqli_fetch_array($query)){                          
    $therow1 = $row['r1'];
    $therow2 = $row['r2'];
    $therow3 = $row['r3'];//get
    $therow4 = $row['r4'];//get
    $the_array[] = [$therow3, $therow4];
}

Javascript:

<script type="text/javascript">
    var locations = JSON.parse('<?php echo json_encode($the_array); ?>');

</script>
Ismail RBOUH
  • 10,292
  • 2
  • 24
  • 36
  • This just give me ["1","20","10","11","10","120"] , should be [[1,20],[10,11],[10,120]] – c.k Jul 13 '16 at 03:06