简体   繁体   English

无法从php输入数组到javascript

[英]Can't input array from php to javascript

I have this code: 我有这个代码:

<?php $result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$result[] = sprintf("{lat: %s, lng: %s}",$row['lat'],$row['lng']);} ?>

<?php $resultAM = join(', ',$result);
echo $resultAM; ?>

the $resultAM represents this result (anyway I'm using SQL): $ resultAM表示此结果(无论如何我使用SQL):

{lat: -7.0476101, lng: 112.7323577}, {lat: -7.0319093, lng: 112.7614287}, {lat: -7.0433001, lng: 112.7606889}, {lat: -7.0459718, lng: 112.7583679}

I'm going to put the code in javascript with this code: 我将使用以下代码将代码放在javascript中:

var distanceM = [<?php echo json_encode($resultAM); ?>];

but the result wont appear. 但结果不会出现。

Anyone can help me? 有人可以帮帮我吗? I'm new at PHP. 我是PHP的新手。 Thanks! 谢谢!

PHP 2D Array can simply transform into JS Array of objects. PHP 2D Array可以简单地转换为JS Array对象。 For example, we have a php array: 例如,我们有一个php数组:

$arr = array('city1' => array('TBILISI' => 'Georgia'), 'city2' => array('LONDON' => 'UK'));

In JS we can simply write: JS我们可以简单地写:

let myArr = <?php echo json_encode($arr); ?>;
console.log(myArr); // Console it..

it now looks in JS like that: 它现在看起来像JS那样:

{"city1":
       {"TBILISI": "Georgia"},
"city2": 
       {"LONDON": "UK"}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM