Recursive replacement of array keys

I have a rather large recursive array with mixed numeric and string keys.

What is the fastest way to replace numeric keys with string keys (prefix each number 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 elements to remain the same.

+4
source share
1 answer
 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; } 
+5
source

All Articles