Voting

: eight plus one?
(Example: nine)

The Note You're Voting On

anonymous_user
4 years ago
/** 
 * Function which recursively applies a callback to all values and also its
 * keys, and returns the resulting array copy with the updated keys and 
 * values.
 * PHP's built-in function array_walk_recursive() only applies the passed 
 * callback to the array values, not the keys, so this function simply applies
 * the callback to the keys too (hence the need of working with a copy, 
 * as also updating the keys would lead to reference loss of the original
 * array). I needed something like this, hence my idea of sharing it here.
 *
 * @param callable $func callback which takes one parameter (value 
 * or key to be updated) and returns its 
 * updated value
 *
 * @param array $arr array of which keys and values shall be 
 * get updated 
 */
function array_map_recursive(
 callable $func,
 array $arr
) {
 // Initiate copied array which will hold all updated keys + values
 $result = [];
 // Iterate through the key-value pairs of the array
 foreach ( $arr as $key => $value ) {
 // Apply the callback to the key to create the updated key value
 $updated_key = $func( $key );
 // If the iterated value is not an array, that means we have reached the
 // deepest array level for the iterated key, so in that case, assign
 // the updated value to the updated key value in the final output array
 if ( ! is_array( $value ) ) {
 $result[$updated_key] = $func( $value );
 } else {
 // If the iterated value is an array, call the function recursively,
 // By taking the currently iterated value as the $arr argument
 $result[$updated_key] = array_map_recursive(
 $func,
 $arr[$key]
 );
 }
 } // end of iteration through k-v pairs
 // And at the very end, return the generated result set
 return $result;
 } // end of array_map_recursive() function definition

<< Back to user notes page

AltStyle によって変換されたページ (->オリジナル) /