0

我有这个 javascript 数组

   <script>
$(function() {
 var foo= [ "one",
            "two",
            "three",
            "one",
            "final"];
</script>

现在,我正在尝试foo用 PHP 数组替换 。

<?php $array = array("sky","mac","rain","bob","sep","ion"); ?>

现在,我试过了

<script>
    $(function() {
     var foo= [<?php array("sky","mac","rain","bob","sep","ion"); ?> ];
    </script>

但是,它似乎不起作用

4

2 回答 2

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>
于 2013-03-03T12:49:08.700 回答
0
var foo= ['<?php print implode("','", array("sky","mac","rain","bob","sep","ion")); ?>'];
于 2013-03-03T12:44:27.607 回答