Using iterator_to_array() in PHP
iterator_to_array()
before. I’m sure they weren’t alone and since I just typed it again, I thought I’d share a snippet.Mostly I find this useful when I’m working with collections of data as these often present themselves as an object that you can
foreach()
over, but you can’t dump it directly. If the object in question implements the Traversable interface, you can instead pass it into iterator_to_array to get the data as an array.
Consider for example my code which finds records in a MongoDB database; this returns a MongoCursor object, so when I var_dump()
it, all I get is a little output telling me that’s what sort of an object it is! Using iterator_to_array()
, I can grab an array that I can quickly use to check what I got back:
$people = $db->people->find()->sort(array("created" => -1));
print_r(iterator_to_array($people));
In this case, I know there are only two rows in my database so it is a useful diagnostic tool as I put in the first pieces of a new application. Do be careful though about using this function on potentially large datasets! One of the best things about cursors is precisely that they avoid bringing in everything in one go, in case the data set is too large, so there are times when you won’t want to put it all into an array at once. However for the times when you do – now you can :)
Good to know, thx!
Great info Lorna. Another thing to note about iterator_to_array. If you have a RecursiveIterator, on possibly a multi-dimensional array, it will flatten your data. Just something to keep in mind.
Good point, I didn’t think to mention about nested data so I’m glad you did :)
@Jake Only if you “to array” a RecursiveIteratorIterator.
Thx for sharing. I never saw this function before either.
This function is also very handy if you want to use things like array_map on collections. Oh how I wait for the day when all array funcs support traversables…
Pingback: Lorna Mitchell’s Blog: Using iterator_to_array() in PHP | Scripting4You Blog
Pingback: Using iterator_to_array() in PHP | LornaJane | Bloc notes PHP | Scoop.it
Thought I’d point out that instead of using a specific server and language full URL to the PHP manual entry (in this case uk3.php.net/manual/en/…), you can let their servers figure that out:
http://php.net/iterator_to_array
FYI – John
Here is a class method I use to convert a SimpleXMLIterator for a structure of arbitrary depth to an array:
[code]
itToArray($a);
}
}
return $array;
}
}
?>
[/code]
Feel free to delete my obvious post-before-I-read comment without code tags ;)