简体   繁体   中英

Issue in iterating MongoCursor using foreach loop with php

I am trying to iterate the MongoCursor using the foreach loop as shown in the code below. The loop only returns the first record. Can anyone figure out what the issue is?

Here is my code

$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++;
}

The output of print_r is

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 ) ) ) ) 

The MongoDb schema is below

{
 "_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"
 }
}

Try this.

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

The problem is that find() returns a pointer, not a result. The foreach that you are iterating just fetches all to rows and to do what you want you need another loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM