Possible Duplicate:
Fastest way to add prefix to array keys?
I had a quick question about arrays in PHP. I need to add a couple of characters to each key i开发者_StackOverflown an array, for instance:
name => Mark age => 23 weight = > 150
needs to be converted to:
r_name => Mark r_age => 23 r_weight => 150
Any help would be appreciated, thanks.
Iterate the array, add a new item with the modified key and delete the original item:
foreach ($arr as $key => $val) {
$arr['r_'.$key] = $val;
unset($arr[$key]);
}
As foreach
works with an internal copy of the array, you won’t run into an infinite loop.
Take a look at this post: In PHP, how do you change the key of an array element?
If you can be sure, that there are no two keys $K1,$K2 in your array with $K1 = "r_".$K2 , you can use the solution given by Gumbo - its efficient and nice.
If you can not guarantee the stated condition, i would prefer generating a new array with the altered keys and deleting/overwriting the old one afterwards. This is not as memory efficient as the other solution but wont fail.
Another thing to keep in mind is, that unset is a bit slow in PHP. So Unsetting a lot of elements in your array might be slower than working with a copy and deleting the original afterwards.
精彩评论