函式名:MongoDB\BSON\Document::getIterator()
適用版本:PHP 5.6.0以上,MongoDB Extension 1.0.0以上
函式說明:該函式用於返回一個迭代器,用於遍歷MongoDB\BSON\Document物件中的所有元素。
用法示例:
// 建立一個MongoDB\BSON\Document物件
$document = new MongoDB\BSON\Document([
'name' => 'John Doe',
'age' => 30,
'email' => '[email protected]'
]);
// 使用getIterator()方法獲取迭代器
$iterator = $document->getIterator();
// 使用foreach迴圈遍歷Document物件的所有元素
foreach ($iterator as $key => $value) {
echo $key . ': ' . $value . PHP_EOL;
}
輸出結果:
name: John Doe
age: 30
email: [email protected]
在上面的示例中,我們首先建立了一個MongoDB\BSON\Document物件,該物件包含了名字、年齡和電子郵件地址等欄位。然後,我們使用getIterator()方法獲取一個迭代器物件,用於遍歷Document物件中的所有元素。最後,我們使用foreach迴圈來遍歷迭代器,並輸出每個元素的鍵和值。
請注意,getIterator()方法返回的迭代器物件是PHP內建的ArrayIterator類的例項,因此可以使用所有ArrayIterator類的方法來操作迭代器,例如使用current()、key()和next()等方法。