2016-04-19 36 views
0

代碼:的MongoDB和Twitter陣列

$m = new MongoClient(); 
$db = $m->selectDB('twitter'); 
$collection = new MongoCollection($db, 'status'); 
$cursor = $collection->find(); 
foreach ($cursor as $document) { 
    echo $document['statuses'][0]['text']; 
} 

陣:

Array 
(
    [_id] => MongoId Object 
    (
     [$id] => 123 
    ) 

    [statuses] => Array 
    (
     [0] => Array 
      (
      [text] => Tweet no 1 
      ) 
     [1] => Array 
      (
      [text] => Tweet no 2 
      ) 
     [1] => Array 
      (
      [text] => Tweet no 3 
      ) 
    ) 
) 

輸出:鳴叫沒有1.

如何獲得整個 '文本' 數組?它應該返回'Tweet no 1,Tweet no 2,Tweet no 3'。我試過echo $document['statuses']['text'],但不起作用。

回答

1

現在你的查詢正在返回一個集合,所以你正在迭代它。問題是它是一個只有單個文檔的集合,並且僅打印該文檔中的第一個狀態:

foreach ($cursor as $document) { 
    // here $document = {_id: 123, statuses:[{text:'Tweet no 1'},{text:'Tweet no 2'},{text:'Tweet no 3'}]} 
    // here you are only printing the first status  
    echo $document['statuses'][0]['text']; 
} 

您的文檔有狀態的數組,所以要通過數組循環:

foreach ($cursor as $document) { 
    foreach($document["status"] as $status) { 
     echo $status['text']; 
    } 
}