tags:

views:

57

answers:

1

Hello,

I have quite big recursive array with mixed numeric and string keys.

Which is the fastest way to replace the numeric keys with string keys (prefix each numeric with item_)?

eg.

array('key_1' => 'val1', 2 => array( 3 => 'val3'));

to

array('key_1' => 'val1', 'item_2' => array('item_3' => 'val3'));

I want the order of the items remain the same.

+4  A: 
function replace_numeric_keys(&$array) {
    $result = array();
    foreach ($array as $key => $value) {
        if (is_int($key)) $key = "item_$key";
        if (is_array($value)) $value = replace_numeric_keys($value);
        $result[$key] = $value;
    }
    return $result;
}
Sean Huber
+1 That's pretty much what I would do...
ircmaxell
@Sean, And the same using tail recursion would be?
takeshin
@takeshin The recursive call is inside a loop.
jleedev
I'm not sure you can use tail recursion since you're modifying the key and hence need to do something with the result of the recursive call (if it was only the value, it would be easy). Feel free to correct me if I'm wrong...
ircmaxell