Created
June 25, 2012 17:19
-
-
Save mlconnor/2989980 to your computer and use it in GitHub Desktop.
php function to walk an array/object recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you man, you don't have a minimum idea of how this thing helped me