2016-07-12 94 views
-1

我有這樣的代碼從數據庫PHP循環數組的JavaScript陣列

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

} 

獲取所有數據我怎樣才能獲得$therow3$therow3作爲一個數組,然後把它傳遞JavaScript作爲數組。

JavaScript數組中的預期結果將是: $ the_array

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

然後,我會用這個數組中的JavaScript

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

</script> 
+0

$ the_array [$ therow3] = $行[ 'R3']; –

+0

http://php.net/manual/en/language.types.array.php – Andreas

+0

[如何將變量和數據從PHP傳遞到JavaScript?](http://stackoverflow.com/questions/23740548/如何通過變量和數據從php到JavaScript) – aghidini

回答

0

請試試這個:

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> 
+0

這只是給我[「1」,「20」,「10」,「11」,「10」,「120」] ,應該是[[1,20],[10,11],[10,120]] –

+0

Okey!我已經更新了我的答案,請查看。 –

0

要在格式JavaScript能夠理解發送陣列,您需要在PHP中將其編碼爲JSON,然後在Javascript中將其解碼,然後在Javascript中對其進行解碼

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

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