note 20220 modified in function.array-map by aidan
| From: | aidan@php.net | Date: | Tue, 06 Jul 2004 08:30:39 +0000 |
| Subject: | note 20220 modified in function.array-map by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-72721@lists.php.net to get a copy of this message | ||
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.
--was--
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:
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.
http://php.net/manual/en/function.array-map.php