2011-12-21 43 views
6

將MongoCursor轉換爲PHP時,我使用此腳本。這是使用上法這裏 StackOverflowSO將Mongo遊標正確解析爲PHP

提出,該結構是相同的,但是_id而使用較低腳本其產生包含如下結果。

不幸的是,這導致實際的對象被嵌入到Mongo的_id數組中。像這樣:

`4eefa79d76d6fd8b50000007 =    { 
      "_id" =     { 
       "$id" = 4eefa79d76d6fd8b50000007; 
      }; 
      longText = "Error Description"; 
      nCode = dee29fd7e15ce4ab2d3f7dfa7c5d8fc44b27501ad00908771128c920ef276154; 
      nStatus = Process; 
      nText = "E12345"; 
      nVType = Type1; 
      pId =     { 
       "$id" = 4eefa79676d6fd8b50000003; 
      }; 
      pushDate = "2011-12-20+06%3A07%3A41"; 
      updateFlag = 1; 
     };` 

因爲我將此對象傳遞給另一個處理_id的服務未知。

我該如何說服PHP驅動程序正確解析對象?

+0

我不明白你的問題 – Petrogad 2011-12-21 13:45:34

+0

的問題是,ID是越來越嵌套,但我們需要他們發佈他們的代碼。請發佈您的代碼user1094824。 – 2011-12-21 16:09:29

+0

包含'$ id'的'_id'實際上是預期的,因爲他的文檔包含一個MongoId對象(由MongoId類/對象php返回的mongo生成的關鍵字),用'$ id'表示。 – 2012-04-09 18:08:00

回答

5

基本上我做的是這個。

return json_encode(iterator_to_array($cursor)); 

但是,這創造了上述對象,這不是我所需要的。

我以這種方式解決了這個問題。

$i=0; 

    foreach($cursor as $item){ 
     $return[$i] = array(
      '_id'=>$item['_id'], 
      'nCode'=>$item['nCode'], 
      'pId'=>$item['pId'], 
      'nText'=>$item['nText'], 
      'longText'=>$item['longText'], 
      'nStatus'=>$item['nStatus'], 
      'nVType'=>$item['nVType'], 
      'pushDate'=>$item['pushDate'], 
      'updateFlag'=>$item['updateFlag'], 
      'counter' => $i 
        ); 
     $i++; 
    } 

return json_encode($ return);

2

如果結果是大,爲了節省內存,你可以嘗試這種更有效的方法:

function outIterator($iterator, $resultName='results') 
{ 
    // Efficient MongoCursor Iterator to JSON 
    // instead of encoding the whole result array to json 
    // process each item individually 
    // in order to save memory by not copying the data multiple times 

    //Start Json Output 
    header('Content-Type: application/json'); 
    echo '{' . $resultName . ': [' 

    //Output each item as json if there are results in the iterator  
    if ($iterator->hasNext()){ 
     foreach ($iterator as $item) 
     { 
      echo json_encode ($fixeditem); 
      if ($iterator->hasNext()) echo ', '; 
     } 
    } 

    //end Json output 
    echo ']}'; 
} 

$results = $db->collection->find(); 
outIterator($results);