Created
September 19, 2014 14:59
-
-
Save ralphschindler/9005ca9b44c497fe3be0 to your computer and use it in GitHub Desktop.
Apply user functions to both keys and values while recursively walking an associative array
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
<?php | |
function array_walk_recursive_key(array $array, callable $valueCallback, callable $keyCallback = null) { | |
foreach ($array as $n => &$v) { | |
$n2 = ($keyCallback) ? $keyCallback($n) : $n; | |
if ($n != $n2) { | |
$array[$n2] = &$array[$n]; | |
unset($array[$n]); | |
} | |
if (is_array($v)) { | |
$array[$n2] = array_walk_recursive_key($v, $valueCallback, $keyCallback); | |
} elseif (is_string($v)) { | |
$array[$n2] = $valueCallback($v); | |
} elseif (is_array($v)) { | |
foreach ($v as &$j) { | |
$j = $valueCallback($j); | |
} | |
} | |
} | |
return $array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment