dongpin3794
dongpin3794
2018-05-07 06:51

在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!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doushi5024 doushi5024 3年前

    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 doujie1908 3年前

    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;?>
    
    点赞 评论 复制链接分享

相关推荐