dongmacheng3222
2015-06-05 07:31 浏览 24
已采纳

如何修剪数组中每个键的最后两个字符?

This is my array (input):

$value = array("jan01" => "01", "feb02" => "02", "mar03" => "03", "apr04" => "04");

I am using this code to get the array keys:

implode(" ", array_map("ucwords", array_keys($value)));

Now my problem is I want to get all keys by triming the last two characters of each key.

How can I change/modify my code, so that it trim's the last two characters of each key?

EDIT:

I also want to skip first 3 keys, means I don't want the first 3 keys to be trimmed.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答 默认 最新

  • 已采纳
    douzhi1919 douzhi1919 2015-06-05 07:36

    I think this should work for you:

    Just take the substr() from your key and then use ucwords() on it.

    implode(" ",array_map(function($v){
        return ucwords(substr($v, 0, -2));
    },array_keys($value)));
    

    EDIT:

    AS from your updated question you don't want to take the substr from the first 3 elements. So just use a counter variable, e.g.

    $counter = 1;
    echo implode(" ", array_map(function($v)use(&$counter){
        if($counter++ > 3)
            return ucwords(substr($v, 0, -2));
        return ucwords($v);
    },array_keys($value)));
    
    点赞 评论 复制链接分享
  • dongmeng0317 dongmeng0317 2015-06-05 07:36

    Here's something for undetermined array depth.

    $arr = your array;
    $trimmed_values = array();
    
    array_walk_recursive($arr, function($key, $value) use (&$trimmed_values)
    {
        $trimmed_values[] = substr($key, 0, -2);
    });
    

    This won't work if you're not using PHP 5.3+ as lower versions don't have anonymous functions.

    点赞 评论 复制链接分享

相关推荐