php嵌套的foreach不工作
我得到的结果是:php嵌套的foreach不工作,php,for-loop,foreach,mongodb-php,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 wo
//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";
}
}
这显然缺少第二个for循环回波
仅供参考。“$cursor”只在foreach语句运行时被调用,我想这就是mongoDB-PHP的工作方式。
foreach
只在数组上迭代。
您可以使用
var\u dump($cursor)检查$cursor
的数据类型代码>您的代码缺少一些检查。试试这个:
object G4849756
object A4202291
object O5548422
object O5548513
object D5921405
尝试添加一个var\u转储($cursor)代码>设置后立即查找其中真正的内容。我也在想(我必须确认)在对其使用foreach
之前,您可能需要将其从对象转换为数组。不确定。MongoDB\Driver\Cursor对象([database]=>mfrmls[collection]=>properties[query]=>MongoDB\Driver\query对象([filter]=>stdClass对象([ListingId]=>D5921405)[options]=>stdClass对象([serverId]=>1)[readConcern]=>)
应该对这种类型的对象没有问题。在其他条件下回显某个对象并检查,它是否来自foreach?它是一个对象,MongoDB\Driver\Cursor对象([database]=>mfrmls[collection]=>properties[query]=>MongoDB\Driver\Query对象
//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";
}
}
}