note 94008 modified in function.array-map by danbrown

From: Date: Tue, 13 Oct 2009 15:44:29 +0000
Subject: note 94008 modified in function.array-map by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161694@lists.php.net to get a copy of this message
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; } ?> --was-- 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. /** * 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; } http://php.net/manual/en/function.array-map.php

« previous php.notes (#161694) next »