如何用php数组替换javascript数组?

时间:2013-03-03 12:43:02

标签: php javascript arrays

我有这个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>

但是,似乎没有工作

2 个答案:

答案 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")); ?>'];