Skip to content

Instantly share code, notes, and snippets.

@stephandesouza
Created October 18, 2012 21:08
Show Gist options
  • Save stephandesouza/3914749 to your computer and use it in GitHub Desktop.
Save stephandesouza/3914749 to your computer and use it in GitHub Desktop.
Recursively map a string function from a array/object
<?php
//Array from JSON Webservice
$array = array();
//Decoding all values from UTF-8
str_recursive_map('utf8_decode',$array);
//Applying htmlentities ( Good for other charset )
str_recursive_map('htmlentities',$array);
<?php
if(!function_exists('str_recursive_map')) {
function str_recursive_map($fn,&$input) {
if (is_string($input)) {
$input = $fn($input);
} else if (is_array($input)) {
foreach ($input as &$value) {
str_recursive_map($fn,$value);
}
unset($value);
} else if (is_object($input)) {
$vars = array_keys(get_object_vars($input));
foreach ($vars as $var) {
str_recursive_map($fn,$input->$var);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment