2017-05-09 116 views
0

我對我的mongodb數據庫執行查詢...然後在我的前端邏輯中的兩個單獨的點中,我需要遍歷結果以提取/顯示不同的信息。嘗試迭代mongodb遊標兩次 - 失敗

問題

我第二次嘗試遍歷,我收到以下錯誤信息:

Fatal error: Uncaught MongoDB\Driver\Exception\LogicException: Cursors cannot yield multiple iterators in /var/www/localhost/htdocs/widgets/exception_details.php:46 Stack trace: #0

後端代碼

下面就來查詢數據庫中的邏輯我的型號:

try{ 
     $id = new \MongoDB\BSON\ObjectId($docid); 
     $filter = ['_id' => $id]; 
     $options = []; 
     $query = new \MongoDB\Driver\Query($filter, $options); 
     $rows = $m->executeQuery('widgets.play_summary', $query); 
     return $rows; 
    } catch (Exception $e) { 
     echo 'Exception:'. $e->getMessage(); 
     return false; 
    } 

前端邏輯

下面是試圖迭代的邏輯。

首播時間:

foreach ($rows as $id=>$value) { 
     if (count($value->unreachable_servers > 0)) { 
      foreach($value->unreachable_servers as $key=>$value) { 
       echo "<tr>"; 
       echo "<td>$value</td>"; 
       echo "</tr>"; 
      } 
     } 
} 

再後來,我嘗試這樣做:

$it = new IteratorIterator($rows); //line 46 
$it->rewind(); 
foreach ($rows as $id=>$value) { 
    if (count($value->failed_plays > 0)) { 
      foreach($value->failed_plays as $key=>$value) { 
        echo "<tr>"; 
        echo "<td>$value</td>"; 
        echo "</tr>"; 
      } 
    } 
} 

其他信息

註釋掉以下行會給出確切的同樣的錯誤,只是在線48而不是線46:

$it = new IteratorIterator($rows); 
$it->rewind(); 

任何提示將不勝感激。

謝謝。

EDIT 1

作爲測試,我改變前端代碼以使用倒帶和下一個這樣的:

$it = new \IteratorIterator($rows); 
$it->rewind(); 
//foreach ($rows as $id=>$value) { 
while($value = $it->current()) { 
     if (count($value->unreachable_servers > 0)) { 
      foreach($value->unreachable_servers as $key=>$value) { 
       echo "<tr>"; 
       echo "<td>$value</td>"; 
       echo "</tr>"; 
      } 
     } 
    $it->next(); 
} 

而對於第二個循環:

$it = new IteratorIterator($rows); 
$it->rewind(); 
//foreach ($rows as $id=>$value) { 
while($value = $it->current()) { 
    if (count($value->failed_plays > 0)) { 
      foreach($value->failed_plays as $key=>$value) { 
        echo "<tr>"; 
        echo "<td>$value</td>"; 
        echo "</tr>"; 
      } 
    } 
    $it->next(); 
} 

我得到相同的結果。它第一次運作,但第二次爆炸同樣的錯誤信息。

回答

0

光標不能迭代兩次。如果它適合內存,將它取到數組中:

$rows = $m->executeQuery('widgets.play_summary', $query); 
    return $rows->toArray(); 
+0

那麼他們爲什麼給你一個倒帶方法?我現在正在給你的答案一個嘗試......但只是想我會問。 – dot

+1

**他們**?你是誰,試圖用迭代器來包裝遊標。 –

+0

嗯...所以如果你看看文檔,它明確提到了一個倒帶方法。 http://php.net/manual/en/class.mongodb-driver-cursor.php – dot