note 106684 added to function.array-map
| From: | php/hotblocks/nl at osu1 dot php dot net | Date: | Mon, 28 Nov 2011 13:00:17 +0000 |
| Subject: | note 106684 added to function.array-map | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-184739@lists.php.net to get a copy of this message | ||
Note that the $arr argument has to be an array, not just a Traversable/Iterator.
For instance this won't work:
<?php
$documents = $mongo->db->collection->find();
// $documents is Traversable by foreach
$ids = array_map(function($document) {
return $document['_id'];
}, $objects);
// $ids will now be NULL, because $documents wasn't an Array
?>
A solution is to first use iterator_to_array():
<?php
$ids = array_map(function($document) {
return $document['_id'];
}, iterator_to_array($objects));
// $ids will now be an array of ['_id']s
?>
But this is not very efficient: two cycles instead of one. Another solution is to use foreach: one
cycle and a lot of freedom (and in the same scope).
----
Server IP: 91.199.167.223
Probable Submitter: 213.125.116.82
----
Manual Page -- http://www.php.net/manual/en/function.array-map.php
Edit -- https://master.php.net/note/edit/106684
Del: integrated -- https://master.php.net/note/delete/106684/integrated
Del: useless -- https://master.php.net/note/delete/106684/useless
Del: bad code -- https://master.php.net/note/delete/106684/bad+code
Del: spam -- https://master.php.net/note/delete/106684/spam
Del: non-english -- https://master.php.net/note/delete/106684/non-english
Del: in docs -- https://master.php.net/note/delete/106684/in+docs
Del: other reasons-- https://master.php.net/note/delete/106684
Reject -- https://master.php.net/note/reject/106684
Search -- https://master.php.net/manage/user-notes.php