使用mongoDB和PHP进行迭代

时间:2016-02-10 12:13:47

标签: php mongodb

我有一个测验数据库,其特殊安排如下所示:

"question" : "What are the two binary numbers?",
"answers" : {
    "ch1" : "1 and 0",
    "ch2" : "1 and 2",
    "ch3" : "1 to 9"
},
"rightanswer" : "ch1" }                                                                            

数据库测验中有n个这样的条目。现在我将循环遍历整个数据库并打印每个值。

如何才能在for循环中完成;我只是看起来像question[i]answer.ch1[i]answer.ch2[i] ....如何检索?

var-dump结果:

array(4) { 
    ["_id"]=> object(MongoId)#7 (1) { ["$id"]=> string(24)"56bb13aef9f36fe751eecfe4" } 
    ["question"]=> string(32) What are the two binary numbers?" 
    ["answers"]=> array(3) { 
        ["ch1"]=> string(7) "1 and 0" 
        ["ch2"]=> string(7) "1 and 2" 
        ["ch3"]=> string(6) "1 to 9" 
    } 
    ["rightanswer"]=> string(3) "ch1" 
}
array(4) { 
    ["_id"]=> object(MongoId)#8 (1) { ["$id"]=> string(24) "56bb1714f9f36fe751eecfe5" } 
    ["question"]=> string(51) "It is a standard specifying a power saving feature?" 
    ["answers"]=> array(3) { .....

2 个答案:

答案 0 :(得分:0)

我假设你将连接到集合,代码 collectionName 是表的名称。

$connection = new MongoClient();
$collection = $connection->database->collectionName;

$cursor = $collection->find();
foreach ( $cursor as $id => $value )
{
    echo "$id: ";
    var_dump( $value );
//echo $value->question_id;
//echo $value->answers->ch1;

}

您可以按照自己的方式替换循环内的代码和打印字段名称。

由于 阿米特

答案 1 :(得分:0)

由于您设法使用预期结果打印$obj["question"],因此对答案的迭代必须是:

foreach($obj["answers"] as $key=>$answer) {
    echo "$key: $answer"; //or whatever format you need
}