duanjue6575 2012-08-16 18:53
浏览 74
已采纳

递归更改数组中的键

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

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...

Input:

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

Expected result:

$_POST['Neat key'] = 'dirty value';
  • 写回答

2条回答 默认 最新

  • doupai1876 2012-08-16 19:09
    关注

    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'
            )
    )
    */
    

    Try it: http://codepad.org/A0N5AU2g

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 win c++ socket
  • ¥15 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的