drsw9390405 2018-04-19 19:24
浏览 64
已采纳

带有PHP驱动程序的mongoDB Cursor,与foreach一起迭代

I l looked into PHP Driver for Cursor, but could not find an answer in the spec. Let's say we run this chunk of php code

 $scoresCollection = Score::collection();
        $scoreRecords = $scoresCollection->find(['score.pairID'=>['$exists'=>false]])
            ->sort(['created'=>1])->limit(4);

        foreach ($scoreRecords as $r) { ... 

While looping, is $r an array or a Score Model instance? Does foreach on the Cursor handles the records and converts them to arrays? Is it faster to get as array?

  • 写回答

1条回答 默认 最新

  • duanlu9557 2018-04-19 20:49
    关注

    Per my comment on the original question:

    To my knowledge, the driver returns each document $r represented by an associative array. This is how the PHP driver handles them internally, and the associative arrays are simply converted to the appropriate format by the driver prior to sending them off to the MongoDB instance. As for your question about whether or not it's faster to get the documents as an array, it shouldn't make a difference. Converting to an array is, in essence, running a foreach on the cursor and storing each $r into an array. If anything, it'll be slower because you'll be iterating through the elements twice!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?