array:更改密钥并替换为新密钥

时间:2016-12-21 22:13:08

标签: php

我在stackexchange上发现了很多关于替换密钥的例子,但我无法处理我的情况。我正在尝试两者:使用foreach和array_map(array_walk)但无法完成它。

$arr = ["first_name"=>"a","second_name"=>"","third_name"=>"b"];

$arr = array_map(function($key, $value) {
    $key = str_replace("_name", "", $key);
    return array($key=>$value);
}, array_keys($arr), $arr);
输出应该是:

 $arr = ["first"=>"a","second"=>"","third"=>"b"];

但事实并非如此。你能告诉我两种方式:foreach和array_map,应该怎么做?

1 个答案:

答案 0 :(得分:0)

$arr = ["first_name" => "a","second_name" => "","third_name" => "b"];

foreach($arr as $key => $value) {
        $newkey = str_replace("_name", "", $key);
        $arr[$newkey] = $value;
        unset($arr[$key]);
 }