如何调整数组中每个键的最后两个字符?

时间:2021-06-10 21:48:56

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.

我还想跳过前3个键,这意味着我不希望前3个键被删除。

2 个解决方案

#1


3  

I think this should work for you:

我认为这对你应该有用:

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

只需从键中取出substr(),然后在其上使用ucwords()。

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.

就像你更新的问题一样,你不希望从前三个元素中提取substr。用一个计数器变量。

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

#2


1  

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.

如果您不使用PHP 5.3+,这将不起作用,因为低级版本没有匿名函数。

#1


3  

I think this should work for you:

我认为这对你应该有用:

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

只需从键中取出substr(),然后在其上使用ucwords()。

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.

就像你更新的问题一样,你不希望从前三个元素中提取substr。用一个计数器变量。

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

#2


1  

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.

如果您不使用PHP 5.3+,这将不起作用,因为低级版本没有匿名函数。