我在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,应该怎么做?
答案 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]);
}