-
-
Save Allakazan/2c9dacac4323a4735d2b574056fe5cbe 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