我有一个测验数据库,它有特殊的安排,如下所示:
"question" : "What are the two binary numbers?",
"answers" : {
"ch1" : "1 and 0",
"ch2" : "1 and 2",
"ch3" : "1 to 9"
},
"rightanswer" : "ch1" } DB测验中有n个这样的条目。现在,我将遍历整个DB并打印每个值。
如何在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) { .....发布于 2016-02-10 20:21:44
我假设您将连接到集合,并且在代码中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;
}你可以用你想要的方式在循环中替换代码和打印字段名。
谢谢阿米特
发布于 2016-02-11 17:00:36
由于您成功地打印出了预期结果的$obj["question"],因此答案的迭代必须是:
foreach($obj["answers"] as $key=>$answer) {
echo "$key: $answer"; //or whatever format you need
}https://stackoverflow.com/questions/35314980
复制相似问题