nitin jain
nitin jain

Reputation: 298

replace any specific character in array key

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

I need output like below. array can have multiple level . Its comes with api so we do not know where colon come.

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

Upvotes: 0

Views: 55

Answers (3)

AdamJonR
AdamJonR

Reputation: 4713

This seems like the simplest and most performant approach:

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

Upvotes: 0

Timothée Groleau
Timothée Groleau

Reputation: 1960

(untested code) but the idea should be correct if want to remove ':' from keys:

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

Upvotes: 1

Dinesh
Dinesh

Reputation: 4110

try this:

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

Upvotes: 1

Related Questions