6

将 MongoCursor 转换为 PHP 时,我使用此脚本。此处介绍了 StackOverflow SO

使用上面的方法,结构是相同的,但是 _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 驱动程序正确解析对象?

4

2 回答 2

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++;
   }

返回 json_encode($return);

于 2011-12-22T00:15:01.370 回答
2

如果您的结果很大以节省 RAM,您可以尝试这种更有效的方法:

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);
于 2012-10-01T02:47:48.073 回答