将PHP数组插入Javascript数组

时间:2010-10-12 13:14:22

标签: php javascript arrays

我有一个这样的数组:

Array
(
[0] => Array
    (
        [id] => 9826
        [tag] => "php"
    )

[1] => Array
    (
        [id] => 9680            
        [tag] => "perl"
    )

)

我想将此传递给一个看起来像这样的javascript变量:

var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
    ];

我已经走到了这一步:

var availableTags = [
        <?php
                        foreach($Tags as $tag){
                              echo $tag['tag'];
                        }
                    ?>
    ];

我遇到的问题是在每个标记周围添加双引号,并在每个标记之后插入一个逗号。

我不确定如何做到最好?

5 个答案:

答案 0 :(得分:10)

为自己保留一些代码:

var availableTags = <?php
function get_tag($value) {
    return $value['tag'];
}
echo json_encode(array_map("get_tag", $Tags));
?>

答案 1 :(得分:6)

var availableTags = [
<?php
  $tag_strings = array();
  foreach($Tags as $tag){
        $tag_strings[] = '"'.$tag['tag'].'"';
  }
  echo implode(",", $tag_strings);
  ?>
];

答案 2 :(得分:2)

var availableTags = [
        <?php
                        foreach($Tags as $tag){
                              echo '"'.$tag['tag'].'",';
                        }
                    ?>
    ];

答案 3 :(得分:1)

尝试:

var availableTags = <?php
echo json_encode(array_map(create_function('$v','return $v[\'tag\'];'), $Tags));
?>;

答案 4 :(得分:0)

<?php 
$arr = array(
0 => array("id" => 9826, "tag" => "php"),

1 => array("id" => 9680, "tag" => "perl")
);

$my_array;

foreach($arr as $key=>$val) {
   $my_array[] = $arr[$key]['tag'];
}

$availableTags = json_encode($my_array);
echo $availableTags;
?>