note 20220 added to function.array-map

From: Date: Tue, 26 Mar 2002 20:33:30 +0000
Subject: note 20220 added to function.array-map
Groups: php.notes 
Request: Send a blank email to php-notes+get-28247@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: 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://www.php.net/manual/en/function.array-map.php http://master.php.net/manage/user-notes.php?action=edit+20220 http://master.php.net/manage/user-notes.php?action=delete+20220 http://master.php.net/manage/user-notes.php?action=reject+20220

« previous php.notes (#28247) next »