note 22369 modified in function.array-map by aidan

From: Date: Tue, 06 Jul 2004 08:30:11 +0000
Subject: note 22369 modified in function.array-map by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-72720@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) <?php 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! --was-- 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://php.net/manual/en/function.array-map.php

« previous php.notes (#72720) next »