开发者

PHP Array key change

I have an array like

$arr = array('key1' => 'hello');

Now I need to change key, is there any why I can achieve this

I know I can do this way:

$arr['key2'] = $arr['key1']; u开发者_如何学Pythonnset($arr['key1']);

But, is there any other way?


The way you've done it is the correct way. You cannot modify a key in an associative array. You can only add or remove keys. If you find yourself in need of doing many "key modifications" you may need to step back and evaluate whether you're using the most appropriate data structure for your problem.


If you were a little crazy you could write a function.

function changeKey(array $array, $oldKey, $newKey) {

     if ( ! array_key_exists($array, $oldKey)) {
         return $array;
     }

     $array[$newKey] = $array[$oldKey];
     unset($array[$oldKey]);
     return $array;
}

This will do nothing if the original key isn't present. It will also overwrite existing keys.


Sounds like what this guy did

http://www.jbip.net/content/how-replace-keys-array-php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜