note 22369 added to function.array-map
| From: | dan@php.net | Date: | Sat, 15 Jun 2002 02:07:08 +0000 |
| Subject: | note 22369 added to function.array-map | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-31879@lists.php.net to get a copy of this message | ||
Here is a better, more true version of a deep array_map. The only negative of this function is that
the array is passed by reference, so just be aware of that. (patches welcome)
function array_map_deep(&$in_array, $in_func, $in_args = array(), $in_index = 1) {
// fix people from messing up the index of the value
if ($in_index < 1) {
$in_index = 1;
}
foreach (array_keys($in_array) as $key) {
// we need a reference, not a copy, normal foreach won't do
$value =& $in_array[$key];
// we need to copy args because we are doing
// manipulation on it farther down
$args = $in_args;
if (is_array($value)) {
array_map_deep($value, $in_func, $in_args, $in_index);
}
else {
array_splice($args, $in_index - 1, $in_index - 1, $value);
$value = call_user_func_array($in_func, $args);
}
}
return $in_array;
}
This is a neat function because you can pass an array, a function, and an array of parameters, and
finally, and index of where in the array of parameters for the callback function the contents you
are mapping should get replaced. This index is human based (starts at 1), and can be used in
something like a preg_replace callback, where the contents must be the 3rd index. Enjoy!
--
http://www.php.net/manual/en/function.array-map.php
http://master.php.net/manage/user-notes.php?action=edit+22369
http://master.php.net/manage/user-notes.php?action=delete+22369
http://master.php.net/manage/user-notes.php?action=reject+22369