将Mongo游标正确解析为PHP

将Mongo游标正确解析为PHP,php,mongodb,cursor,bson,Php,Mongodb,Cursor,Bson,将MongoCursor转换为PHP时,我使用此脚本。这是在这里介绍的 使用上面的方法,结构是相同的,但是_id是相反的,而使用下面的脚本会产生下面包含的结果 不幸的是,这导致实际对象被嵌入到一个数组中,该数组的_id来自Mongo。像这样: `4eefa79d76d6fd8b50000007 = { "_id" = { "$id" = 4eefa79d76d6fd8b5000000

将MongoCursor转换为PHP时,我使用此脚本。这是在这里介绍的

使用上面的方法,结构是相同的,但是_id是相反的,而使用下面的脚本会产生下面包含的结果

不幸的是,这导致实际对象被嵌入到一个数组中,该数组的_id来自Mongo。像这样:

`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驱动程序正确解析对象?

基本上我就是这么做的

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)

如果结果很大,为了节省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);

我不理解你的问题问题问题是id被嵌套了,但是我们需要他们发布他们的代码。请将您的代码发布到用户1094824上。包含“$id”的“u id”实际上是意料之中的,因为他的文档包含一个MongoId对象(mongo生成的键,由php作为MongoId类/对象返回),该对象用“$id”表示。