【问题标题】:PHP loop to array to javascript arrayPHP循环到数组到javascript数组
【发布时间】:2016-07-12 07:45:10
【问题描述】:

我有这段代码可以从数据库中获取所有数据

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>

【问题讨论】:

标签: javascript php arrays


【解决方案1】:

请试试这个:

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>

【讨论】:

  • 这只是给我 ["1","20","10","11","10","120"] ,应该是 [[1,20],[10, 11],[10,120]]
【解决方案2】:

要以 JavaScript 理解的格式发送数组,您需要在 PHP 中将其编码为 JSON,然后在 Javascript 中对其进行解码

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2017-05-07
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    相关资源
    最近更新 更多