Ran into a scenario this weekend where I needed to take a sub-document 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 argument 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:

$record  = $mongo->collection->findOne([ 'what' => 'iwaslookingfor' ]);
$sub_doc = iterator_to_array($data['subDoc']);

If you need to to grab multiple records, which will return a cursor instead of a document, you will need to do a little extra work:

$records = $mongo->collection->find([ 'what' => 'iwaslookingfor' ]);
$records = iterator_to_array($records);

    function (&$record)
      if (isset($record['subDoc'])) {
        $record['subDoc'] = iterator_to_array($record['subDoc']);

Now every subDoc (if present) will be converted to an array!

Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: