$array['a:b']['c:d'] = 'test';
$array['a:b']['e:f']= 'abc';
我需要如下的输出。数组可以有多个级别。它带有api,所以我们不知道冒号来自哪里。替换阵列密钥中的任何特定字符
$array['ab']['cd'] = 'test';
$array['ab']['ef']= 'abc';
$array['a:b']['c:d'] = 'test';
$array['a:b']['e:f']= 'abc';
我需要如下的输出。数组可以有多个级别。它带有api,所以我们不知道冒号来自哪里。替换阵列密钥中的任何特定字符
$array['ab']['cd'] = 'test';
$array['ab']['ef']= 'abc';
(未测试的代码),但如果要删除的思路应该是正确的 ':' 从键:
function clean_keys(&$array)
{
// it's bad to modify the array being iterated on, so we do this in 2 steps:
// find the affected keys first
// then move then in a second loop
$to_move = array();
forach($array as $key => $value) {
if (strpos($key, ':') >= 0) {
$target_key = str_replace(':','', $key);
if (array_key_exists($target_key, $array)) {
throw new Exception('Key conflict detected: ' . $key . ' -> ' . $target_key);
}
array_push($to_move, array(
"old_key" => $key,
"new_key" => $target_key
));
}
// recursive descent
if (is_array($value)) {
clean_keys($array[$key]);
}
}
foreach($to_move as $map) {
$array[$map["new_key"]] = $array[$map["old_key"]];
unset($array[$map["old_key"]]);
}
}
试试这个:
$array=array();
$array[str_replace(':','','a:b')][str_replace(':','','c:d')]="test";
print_r($array);
没有固定密钥。键可以是“def:acc”之类的任何东西。但如果结肠即将到来需要更换 – 2015-02-09 06:47:47
这似乎是最简单,最高性能的方法:
foreach ($array as $key => $val) {
$newArray[str_replace($search, $replace, $key)] = $val;
}
我得到了解决方案和其下工作正常。函数str_replace_json($ search,$ replace,$ subject){ return json_decode(str_replace($ search,$ replace,json_encode($ subject))); – 2015-02-09 07:12:50