note 20220 deleted from function.array-map by philip
| From: | philip@php.net | Date: | Thu, 22 Feb 2007 02:04:39 +0000 |
| Subject: | note 20220 deleted from function.array-map by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-123697@lists.php.net to get a copy of this message | ||
Note Submitter: bishop
----
Sometimes you might be interested in performing a "deep" map, where you apply the callback
to all elements in the array, even if the elements are stuck deep inside of some
array(array(array(...))) business.
Here's an example PHP4 function that handles this case, with a little bit more flexible (and
potentially more error-prone) callback parameter:
<?php
function deepmap($cb, $x) {
if (is_array($x)) {
$it = array();
foreach ($x as $k => $v) {
$it["$k"] = deepmap($cb, $x["$k"]);
}
return $it;
} else {
$cmd = "return (" .
str_replace('$__', $x, $cb) .
");";
return eval($cmd);
}
}
So, you could do, for example:
$some_odds = array(1, 3, 5);
$some_evens = array(0, 2, 4, 6);
$some_nums = array($some_odds, array($some_evens));
deepmap('pow($__, 2)', $some_odds);
deepmap('pow($__, 2)', $some_nums);
?>
Both examples square each element of the arrays, making sure to keep the array structure intact.
Note that the callback function needs to be a) quoted, and b) include the special string $__ (dollar
double underscore); deepmap replaces $__ in the function call with whatever the current element is.