note 107808 added to function.array-map
| From: | qeremy | Date: | Wed, 07 Mar 2012 10:35:02 +0000 |
| Subject: | note 107808 added to function.array-map | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-186516@lists.php.net to get a copy of this message | ||
An alternative for recursive mapping;
<?php
function array_map_recursive($fn, $arr) {
$rarr = array();
foreach ($arr as $k => $v) {
$rarr[$k] = is_array($v)
? array_map_recursive($fn, $v)
: $fn($v); // or call_user_func($fn, $v)
}
return $rarr;
}
function sqr($x) {
return "$x ^ 2 = ". ($x * $x);
}
$a = array(1, 2, 3, array(4, array(5)));
$b = array_map_recursive("sqr", $a);
print_r($b);
?>
Array
(
[0] => 1 ^ 2 = 1
[1] => 2 ^ 2 = 4
[2] => 3 ^ 2 = 9
[3] => Array
(
[0] => 4 ^ 2 = 16
[1] => Array
(
[0] => 5 ^ 2 = 25
)
)
)
----
Server IP: 69.147.83.197
Probable Submitter: 194.27.149.90
----
Manual Page -- http://www.php.net/manual/en/function.array-map.php
Edit -- https://master.php.net/note/edit/107808
Del: integrated -- https://master.php.net/note/delete/107808/integrated
Del: useless -- https://master.php.net/note/delete/107808/useless
Del: bad code -- https://master.php.net/note/delete/107808/bad+code
Del: spam -- https://master.php.net/note/delete/107808/spam
Del: non-english -- https://master.php.net/note/delete/107808/non-english
Del: in docs -- https://master.php.net/note/delete/107808/in+docs
Del: other reasons-- https://master.php.net/note/delete/107808
Reject -- https://master.php.net/note/reject/107808
Search -- https://master.php.net/manage/user-notes.php