dongpin3794
2018-05-07 06:51
浏览 65

在For循环中将PHP变量存储到JavaScript变量中

I know how to pass a PHP variable into JavaScript variable one by one, but now I wish to pass a bunch of variable in a For loop and I just stuck.

<?php
        $m = new MongoClient();
        $db = $m->data_from_tweeter;
        $collection = $db->output;
        $cursor = $collection->find();
        foreach($cursor as $document){
            echo $document['place'] ;
            echo $document['fir'];
            echo $document['sec'];
        }
?>

I want to store 'place' as a String variable, 'fir' and 'sec' as two Num variables, and make them look like:

var num_1 {
    some_place : some_fir,
    some_place : some_fir,
    some_place : some_fir,
    ....
}

and

var num_2 {
    some_place : some_sec,
    some_place : some_sec,
    some_place : some_sec,
    ....
}

How can I make it? Thanks in advance!

图片转代码服务由CSDN问答提供 功能建议

我知道如何将PHP变量逐个传递给JavaScript变量,但现在我希望传递一堆 For循环中的变量,我只是卡住了。

 &lt;?php 
 $ m = new MongoClient(); 
 $ db = $ m-&gt; data_from_tweeter; 
 $ collection = $ db-&gt; 输出; 
 $ cursor = $ collection-&gt; find(); 
 foreach($ cursor as $ document){
 echo $ document ['place']; 
 echo $ document ['fir']; \  n echo $ document ['sec']; 
} 
?&gt; 
   
 
 

我想将'place'存储为String变量'fir' 和'sec'作为两个Num变量,并使它们看起来像:

  var num_1 {
 some_place:some_fir,
 some_place:some_fir,
 some_place:some_fir,  
 .... 
} 
   
 
 

  var num_2 {
 some_place:some_sec,  
 some_place:some_sec,
 some_place:some_sec,
 .... 
} 
   
 
 

我该如何制作? 提前致谢!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doushi5024 2018-05-07 07:16
    已采纳

    The following code snippet might help get you started:

    $num_1 = "var num_1 = {
    ";
    $num_2 = "var num_2 = {
    ";
    foreach ($cursor as $document) {
            $num_1 .= "    {$document['place']} : {$document['fir']},
    ";
            $num_2 .= "    {$document['place']} : {$document['sec']},
    ";
    }  
    $num_1 .= "};
    ";
    $num_2 .= "};
    ";
    
    echo $num_1;
    echo $num_2;
    
    打赏 评论
  • doujie1908 2018-05-07 07:07

    if $document['fir'] and $document['sec'] are array .You can do like this

    <?php
    $m = new MongoClient();
    $db = $m->data_from_tweeter;
    $collection = $db->output;
    $cursor = $collection->find();
    $num1=array();
    $num2=array();
    foreach($cursor as $document){
        echo $document['place'] ;
        $num1 = json_encode ($document['fir']);
        $num2 = json_encode ($document['sec']);
    }
    ?>
    

    You can use a JSON string as a object for javascript

    var num_1  = <?php echo $num1;?>
    var num_2  = <?php echo $num2;?>
    
    打赏 评论

相关推荐 更多相似问题