根据数组为查询分配变量

时间:2013-02-19 19:35:16

标签: php javascript arrays associative-array

我想从查询中获取PHP变量

?q=aaa

并根据关联数组在JS中定义变量:

{
    "aaa": "111",
    "bbb": "222",
    "ccc": "333"
};

所以,如果

var oldVariable = '<?php echo $q; ?>' ; 

然后

var newVariable = ...   // '222' when $q is 'bbb'

1 个答案:

答案 0 :(得分:1)

享受:

<script>
<?php $q =  (isset($_GET['q'])) ? $_GET['q'] : "default" ;?>

var arr = {
    "aaa": "111",
    "bbb": "222",
    "ccc": "333"
};

var oldVariable = '<?php echo $q ; ?>' ;
var newVariable = (typeof arr['<?php echo $q ; ?>'] != "undefined") ? arr['<?php echo $q ; ?>'] : "No var from get" ;

alert(newVariable) ;

</script>