0

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!

1
  • Object keys can't be the same in the same object. Change your object structure. Commented May 7, 2018 at 7:17

2 Answers 2

1

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;?>
Sign up to request clarification or add additional context in comments.

Comments

0

The following code snippet might help get you started:

$num_1 = "var num_1 = {\n";
$num_2 = "var num_2 = {\n";
foreach ($cursor as $document) {
        $num_1 .= "    {$document['place']} : {$document['fir']},\n";
        $num_2 .= "    {$document['place']} : {$document['sec']},\n";
}  
$num_1 .= "};\n";
$num_2 .= "};\n";

echo $num_1;
echo $num_2;

1 Comment

Thanks! Make sense a lot to me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.