Ran into a scenario this weekend where I needed to take a subdocument from Mongo but I needed it in an array in PHP. Reading the data from Mongo with PHP was simple and won’t be discussed. What I’d like to talk about is taking the BSONDocument that Mongo returns and converting it into an array.
I did a bit of searching and most solutions involved iterating through the BSONDocument and creating an array from that. Iterating… wait, iterators are what does that. I have an idea!!
As of PHP 5.1 you can use the
iterator_to_array function. You can pass it an
iterator (like an
ArrayIterator) and it will spit back an array. Optionally
you can pass a second arguement of
false and get an array instead of an
associative array (which is the default).
The function’s first argument is supposed to be a traversable interface. I wasn’t entirely sure if that’s what I was working with but figured what the hell. Turns out the BSONDocument was a traversable interface so in return I received an associative array based on the BSONDocument I passed in.
Not much to the code either:
$data = $mongo->collection->findOne([ 'what' => 'iwaslookingfor' ]); $array = iterator_to_array($data['subDoc']);