$jokes = $collection->find();
How do I convert $jokes
into an array?
You can use PHP's iterator_to_array
function, as suggested in example 1 of the MongoCursor
docs:
$jokes = $collection->find();
$jokesArray = iterator_to_array($jokes);
As a side note to Chris's answer:
array iterator_to_array ( Traversable $iterator [, bool $use_keys = true ] )
Pay attention to the optional second parameter, if it's set to true (default), the final array will be indexed using the "_id" field from each document.
If you applied a sort in the mongo query, the final array might not be what you expected, meaning that the sort order will not be preserved (unless you set the $use_keys parameter to false)
iterator_to_array is not working for nesting more than 2 levels,
Using typeMap you can convert root and its document to array, It will work for any level of nesting
findOne($filter,$options)
$options = ["typeMap" => ['root' => 'array', 'document' => 'array']];
$collection->findOne(['myId' => $id ], $options); // returns array
find($filter,$options)
$options = ["typeMap" => ['root' => 'array', 'document' => 'array']];
$collection->find(['myId' => $id ], $options)->toArray();
iterator_to_array()
forces the driver to load all of the results into memory, so do not do this for result sets that are larger than memory!
use this
$jokes = $collection->find();
foreach ($jokes as $joke) {
var_dump($joke);
}
a lot easier:
findeOne()->getArrayCopy();
as mentioned before: beware from loading large resultsets and convert them to an array
you can also set your preferences with the typeMap option
'typeMap' =>[
'document' => 'array',
'root' => 'array'
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With