如何将php数组转换为js数组?

时间:2013-06-11 06:15:22

标签: php javascript google-maps

我有一个需要转换的php数组并将其分配给var locationsArray

所需格式:

var locationsArray = [
    ['Google Official','1600 Amphitheatre Parkway, Mountain View, USA'],
    ['Google 1','112 S. Main St., Ann Arbor, USA'], 
    ['Google 2','10 10th Street NE, Suite 600 USA']
];

4 个答案:

答案 0 :(得分:2)

    foreach ($address as $key => $val){
                                    $val = strip_tags($val);
                                    $points[] = array($val, $val);
                                }
                                $json = json_encode($points);
                                $json = str_replace('\n',' ',$json);
                                $json = str_replace('\r',' ',$json);

var locations = '<?php echo $json;?>';
var locations_array = JSON.parse(locations);

var locationsArray = locations_array;

答案 1 :(得分:0)

尝试

$NewJsonData = json_encode(locationsArray);
echo $NewJsonData;  //Alert it in javascript   

试试这个LINK

您可以将变量$ NewJsonData分配给您的js变量

答案 2 :(得分:0)

这将是:

<script type="text/javascript">
    var locationsArray = <?php echo json_encode(array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5)); ?>
</script>

不知道php语法,对不起:) ref

答案 3 :(得分:0)

这会对你有帮助。

<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>