递归更改数组中的键 [英] Recursively change keys in array

查看:55
本文介绍了递归更改数组中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 trimmer 函数,它递归地修剪数组中的所有值(人们无缘无故地放了很多空格!):

I have this trimmer function, it recursively trims all values in array (people put tons of spaces for no reason!):

function trimmer(&$var) {
    if (is_array($var)) {
        foreach($var as &$v) {
            trimmer($v);
        }
    }
    else {
        $var = trim($var);
    }
}
trimer($_POST);

问题:我想添加新功能:我希望此功能也将键中的所有 _(下划线)转换为空格.我知道如何转换键 (str_replace('_', ' ', $key)),但我很难让它以这种递归方式工作......

PROBLEM: I would like to add new feature: i want this function also to convert all _ (underscore) in keys to spaces. I know how to convert keys (str_replace('_', ' ', $key)), but i have trouble to make it work in this recursive style...

输入:

$_POST['Neat_key'] = '   dirty value ';

预期结果:

$_POST['Neat key'] = 'dirty value';

推荐答案

不幸的是,没有办法在循环数组时替换数组的键.这是语言的一部分,解决它的唯一方法是使用临时数组:

Unfortunately, there isn't a way to replace the keys of an array while you loop the array. This is a part of the language, the only way around it is to use a temporary array:

$my_array = array(
    'test_key_1'=>'test value 1     ',
    'test_key_2'=>'        omg I love spaces!!         ',
    'test_key_3'=>array(
        'test_subkey_1'=>'SPPPPAAAAACCCEEESSS!!!111    ',
        'testsubkey2'=>'    The best part about computers is the SPACE BUTTON             '
    )
);
function trimmer(&$var) {
    if (is_array($var)) {
        $final = array();
        foreach($var as $k=>&$v) {
            $k = str_replace('_', ' ', $k);
            trimmer($v);
            $final[$k] = $v;
        }
        $var = $final;
    } elseif (is_string($var)) {
        $var = trim($var);
    }
}
/* output
array (
        'test key 1'=>'test value 1',
        'test key 2'=>'omg I love spaces!!',
        'test key 3'=>array (
                'test subkey 1'=>'SPPPPAAAAACCCEEESSS!!!111',
                'testsubkey2'=>'The best part about computers is the SPACE BUTTON'
        )
)
*/

试试看:http://codepad.org/A0N5AU2g

这篇关于递归更改数组中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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