使用带有php的foreach循环迭代MongoCursor的问题

时间:2013-12-11 10:50:36

标签: php mongodb

我正在尝试使用foreach循环迭代MongoCursor,如下面的代码所示。循环仅返回第一个记录。任何人都可以找出问题所在吗?

这是我的代码

$usrcollection = $db->users;
$user = new MongoId($userid);
$where = array('_id' => $user);
$filter = array('courses.coursename' =>true, 'courses.startdate' => true,'courses.duration' =>  true, 'courses.status' => true,'courses.completed' => true,'courses.institute' => true,'courses.instructor' => true,'courses.coursecreated' => true,  '_id' => 0);
$usercursor = $usrcollection->find($where,$filter);

$j = 0; 
foreach ($usercursor as $value) {
    echo($value['courses'][$j]['coursename']);      
    $j++;
}

print_r的输出是

Array ( [courses] => Array ( [0] => Array ( [coursename] => Machine learning [startdate] => 2013-12-01 [duration] => 12 Weeks [institute] => Standford University [instructor] => Dr Lafore [status] => Inprogress [completed] => 20 [coursecreated] => MongoDate Object ( [sec] => 1386751059 [usec] => 0 ) ) [1] => Array ( [coursename] => Fashion Design [startdate] => 2013-12-10 [duration] => 3 Weeks [institute] => MIT [instructor] => Ebay [status] => Inprogress [completed] => 0 [coursecreated] => MongoDate Object ( [sec] => 1386753755 [usec] => 0 ) ) ) ) 

MongoDb架构位于

之下
{
 "_id": ObjectId("52972705f770dff815000002"),
 "badge": "Gold",
 "badgecount": NumberInt(3),
 "badgedate": ISODate("2013-11-13T05:53:49.0Z"),
 "badges": {
 "0": {
   "badgename": "Silver",
   "achievedon": ISODate("2013-10-05T05:53:49.0Z")
  },
 "1": {
   "badgename": "Gold",
   "achievedon": ISODate("2013-11-13T05:53:49.0Z")
  }
 },
"courses": {
 "0": {
   "coursename": "Machine learning",
   "startdate": "2013-12-01",
   "duration": "12 Weeks",
   "institute": "Standford University",
   "instructor": "Dr Lafore ",
   "status": "Inprogress",
   "completed": "20",
   "coursecreated": ISODate("2013-12-11T08:37:39.0Z")
   },
  "1": {
   "coursename": "Fashion Design",
   "startdate": "2013-12-10",
   "duration": "3 Weeks",
   "institute": "MIT",
   "instructor": "Ebay",
   "status": "Inprogress",
   "completed": NumberInt(0),
   "coursecreated": ISODate("2013-12-11T09:22:35.0Z")
  }
 },
 "datejoined": ISODate("2013-10-01T05:53:49.0Z"),
 "education": {
  "0": "Msc Computer science"
 }
}

1 个答案:

答案 0 :(得分:0)

试试这个。

foreach ($usercursor as $value) {
  for($i = 0; $i < count($value['courses']); $i++) {
       echo($value['courses'][$i]['coursename']);    
  }
}

问题是find()返回一个指针,而不是结果。您正在迭代的foreach只是将所有行提取到行并执行您想要的另一个循环。