PHP变量作为Javascript变量名

PHP variable as Javascript variable name

本文关键字:Javascript 变量名 变量 PHP      更新时间:2023-09-26

我知道这类帖子经常出现在互联网上。但我的问题有点棘手,我没有找到答案。

我想在一个带有变量名的循环中用Javascript创建一个关联数组。($JJ=对象表)($JJ->getResto($DB,$acad)允许我恢复数据库数据)

$JJ = new RestaU();  
$JJ = $JJ->getResto($DB,$acad);
    for ($i = 0; $i <= sizeof($JJ)-1; $i++) {
        //Datas recovering
        $lat = $JJ[$i]->loc_lat;
        $long = $JJ[$i]->loc_long;
        $name = $JJ[$i]->nom;
        $ville = $JJ[$i]->ville;
        //String treatment to avoid spaces
        $ville = str_replace(" ","",$ville);
        $name = str_replace(" ","",$name);
echo <<< SC
    <script>
            //here $ville will contain an google map object associated to the ville name.
            //It means that I need to change it for each "for" loop.
            var $ville = new Object();
            //that is why here I need to have $ville["name"] to generate a table for each city 
            //and have an access to it later.
            $ville+["name"] = new google.maps.LatLng($lat,$long);
            console.log(string2);
    </script>
SC;

我的问题是,我找不到正确的解决方案,例如ville1["name"]。每次代码没有被"解释",这意味着我可以拥有字符串,但它不会创建我的数组。

非常感谢你的想法!

评论中的解决方案我用过:var string="$ville";window[string]["name"]="blabla";

它真的很好用。

php是服务器语言,javascript是clint浏览器语言
事实上,你不能共享变量
但是您可以将变量打印到javascript代码中,如:
<script>
  var myvar = '<?php echo $myvar; ?>';
</script>

如果要将变量从javascript发送到php,则必须使用Ajax
对于阵列

<script>
    <?php
    $array = array('index1'=>'hellow World!','index2'=>'Iran haven`t nuclear bomb');
    echo 'var arryname = new Array();';
    foreach($array as $key=>$val){
      echo "'n arryname['{$key}'] = '{$val}';";
    }
    ?>
</script>