递归地从键中修剪特定字符 [英] Recursively left trim a specific character from keys

查看:35
本文介绍了递归地从键中修剪特定字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能完全解决这个问题...

I can't quite work this out...

我希望会有一个默认的PHP函数来执行此操作,但是似乎没有。 t。我在网上找到的代码似乎不适用于我的情况,因为通常人们只需要修改数组值而不需要修改键。

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?

推荐答案

尝试一下:

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;
}

因此,此代码:

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

print_r(replaceKeys($arr));

将产生(如键盘):

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

)

这篇关于递归地从键中修剪特定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆