php嵌套foreach无法正常工作

时间:2018-03-11 17:21:38

标签: php for-loop foreach mongodb-php

   //connects to mongo
   $collection  = (new MongoDB\Client)->mfrmls->properties;

   //takes array with data from array of objects            
   foreach ($obj as $k => $v){

    //prints to make sure on the right record.  this works fine
    echo "object {$v['ListingId']} \n";

    // creates a query to the mongo DB, which works fine, i have checked via var_dump
    $cursor = $collection->find(['ListingId'  => $v['ListingId']]);

    //this for each will never print anything it just seems to be skipped.
    //if i take it out of the nested foreach it works fine.
    foreach($cursor as $document) {
            echo "no no \n";
            }
    }

我得到的结果是:

object G4849756 
object A4202291 
object O5548422 
object O5548513 
object D5921405 

显然缺少第二个循环回声。

仅供参考。 " $光标"只有在foreach语句运行时才会调用,我想这就是mongoDB - PHP的工作方式。

2 个答案:

答案 0 :(得分:1)

foreach仅迭代数组。 您可以使用$cursor

检查var_dump($cursor);的数据类型

答案 1 :(得分:1)

您的代码遗漏了一些支票。试试这个:

//connects to mongo
   $collection  = (new MongoDB\Client)->mfrmls->properties;

   //takes array with data from array of objects            
   foreach ($obj as $k => $v){

    //prints to make sure on the right record.  this works fine
    echo "object {$v['ListingId']} \n";

    // creates a query to the mongo DB, which works fine, i have checked via  
    $cursor = $collection->find(['ListingId'  => $v['ListingId']]);
print_r( $cursor);
    //this for each will never print anything it just seems to be skipped.
    //if i take it out of the nested foreach it works fine.
    if((is_array($cursor) || is_object($cursor)) && !empty( $cursor)) {
       foreach($cursor as $document) {
            echo "no no \n";
            }
     }
    }