Recursively replace keys in an array

2020-08-25 07:09发布

I can't quite work this out...

I was hoping that there would be a default PHP function to do this, but it seems there isn't. The code I've found online seems to not really work for my situation, since often people have only need to the modify array values and not their keys.

I basically need a recursive function that replaces every key that starts with a '_' with the same key without that symbol....

Has anybody here used something similar before?

2条回答
贪生不怕死
2楼-- · 2020-08-25 07:39

Try this:

function replaceKeys(array $input) {

    $return = array();
    foreach ($input as $key => $value) {
        if (strpos($key, '_') === 0)
            $key = substr($key, 1);

        if (is_array($value))
            $value = replaceKeys($value); 

        $return[$key] = $value;
    }
    return $return;
}

So this code:

$arr = array('_name' => 'John', 
             'ages'  => array(
                  '_first' => 10, 
                  'last'   => 15));

print_r(replaceKeys($arr));

Will produce (as seen on codepad):

Array
(
    [name] => John
    [ages] => Array
        (
            [first] => 10
            [last] => 15
        )

)
查看更多
来,给爷笑一个
3楼-- · 2020-08-25 07:49

Use PHP's native array_walk_recursive()

This seems to be a cleaner solution, with $key passed as a reference in the callback function as follows:

array_walk_recursive($your_array, function ($item, &$key) {
    if (strpos($key, '_') === 0) {
        $key = substr($key, 1);
    }
});
查看更多
登录 后发表回答