简体   繁体   中英

PHP to Javascript array trouble

so I have this code:

var loc = new Array();
        <?php foreach($loc as $key => $val) { ?>
            loc.push('<?php print_r($val); ?>');
        <?php } ?>

The problem is is that it's only showing one value and not more than one, like it should. This is the php array code:

$loc = array($lat, $long);

Any help is greatly appreciated.

Try this:

var loc = <?php echo json_encode($loc); ?>;

You should not use print_r . Let me quote the documentation :

print_r — Prints human-readable information about a variable

Note the part I emphasised. " human-readable ". Just because it looks vaguely like something JavaScript might understand, doesn't mean it is ;) json_encode , on the other hand, is specifically designed to output JSON, which is a subset of the syntax JavaScript accepts for variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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