note 94008 deleted from function.array-map by cmb
| From: | cmb@php.net | Date: | Sun, 25 Aug 2019 09:08:22 +0000 |
| Subject: | note 94008 deleted from function.array-map by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-211998@lists.php.net to get a copy of this message | ||
Note Submitter: onassar at gmail dot com
----
Wrote up my own key preservation function for array mapping. It allows n arguments to be passed, and
should be easy enough to follow if you need to make any mods. If you've got any thoughts let me
know.
<?php
/**
* arrayMap function. Customized array_map function which preserves keys/associate array
indexes.
*
* @access public
* @param callback $callback Callback function to run for each element in each array.
* @param mixed $arr1 An array to run through the callback function.
* @param array $array Variable list of array arugments to run through the callback
function.
* @return array Array containing all the elements of $arr1 after applying the callback
function to each one, recursively, maintain keys.
*/
function arrayMap($callback,$arr1) {
$results = array();
$args = array();
if(func_num_args()>2)
$args = (array) array_shift(array_slice(func_get_args(),2));
foreach($arr1 as $key=>$value) {
if(is_array($value)) {
array_unshift($args,$value);
array_unshift($args,$callback);
$results[$key] =
call_user_func_array(array('self','arrayMap'),$args);
}
else {
array_unshift($args,$value);
$results[$key] = call_user_func_array($callback,$args);
}
}
return $results;
}
?>