替换数组键中的任何特定字符

时间:2015-02-09 06:31:03

标签: php

$array['a:b']['c:d'] = 'test';
$array['a:b']['e:f']= 'abc';

我需要输出如下。数组可以有多个级别。它带有api所以我们不知道冒号来自哪里。

$array['ab']['cd'] = 'test';
$array['ab']['ef']= 'abc';

3 个答案:

答案 0 :(得分:1)

试试这个:

$array=array();
$array[str_replace(':','','a:b')][str_replace(':','','c:d')]="test";
print_r($array);

答案 1 :(得分:1)

(未经测试的代码)但如果想要从键中删除“:”,那么这个想法应该是正确的:

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"]]);
    }
}

答案 2 :(得分:0)

这似乎是最简单,最高效的方法:

foreach ($array as $key => $val) {
    $newArray[str_replace($search, $replace, $key)] = $val;
}