Skip to content

Instantly share code, notes, and snippets.

@mlconnor
Created June 25, 2012 17:19
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mlconnor/2989980 to your computer and use it in GitHub Desktop.
Save mlconnor/2989980 to your computer and use it in GitHub Desktop.
php function to walk an array/object recursively
/**
* works for json objects. will replace all
* keys and values with the result of the
* closure.
*/
function walk_recursive($obj, $closure) {
if ( is_object($obj) ) {
$newObj = new stdClass();
foreach ($obj as $property => $value) {
$newProperty = $closure($property);
$newValue = walk_recursive($value, $closure);
$newObj->$newProperty = $newValue;
}
return $newObj;
} else if ( is_array($obj) ) {
$newArray = array();
foreach ($obj as $key => $value) {
$key = $closure($key);
$newArray[$key] = walk_recursive($value, $closure);
}
return $newArray;
} else {
return $closure($obj);
}
}
@Allakazan
Copy link

Thank you man, you don't have a minimum idea of how this thing helped me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment