简体   繁体   中英

What is the most elegant way to change a key of an array by preserve the order

I have a big associative array with over 1 000 items and I want to rename one key but the order must be preserved.

I don't wont to iterate over the complete array and copy it into a new.

have a look at the array_splice function: http://php.net/manual/en/function.array-splice.php

this will do the job

$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
  $array_keys = array_keys($array);

  $array_keys[array_search('old', $array_keys)] = 'new';

  $array = array_combine($array_keys, $array);
$array[$newkeyname] = $array[$oldkeyname];
unset($array[$oldkeyname]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM