我有这个javascript数组
<script>
$(function() {
var foo= [ "one",
"two",
"three",
"one",
"final"];
</script>
现在,我正在尝试用PHP数组替换foo
。
<?php $array = array("sky","mac","rain","bob","sep","ion"); ?>
现在,我尝试了
<script>
$(function() {
var foo= [<?php array("sky","mac","rain","bob","sep","ion"); ?> ];
</script>
但是,似乎没有工作
答案 0 :(得分:6)
在PHP中,您可以使用方法json_encode()
将大多数PHP数组转换为JSON,这是JavaScript中的合法对象。
<?php $array = array("sky","mac","rain","bob","sep","ion"); ?>
<script>
// ...
var foo = <?php echo json_encode( $array ); ?>;
// ...
</script>
答案 1 :(得分:0)
var foo= ['<?php print implode("','", array("sky","mac","rain","bob","sep","ion")); ?>'];