You can "change" the key of an array element simply by setting the new key and removing the old:

您可以通过设置新密钥并删除旧密钥来“更改”数组元素的键:

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

But this will move the key to the end of the array.

但这会将键移动到数组的末尾。

Is there some elegant way to change the key without changing the order?

是否有一些优雅的方式来改变密钥而不改变顺序?

(PS: This question is just out of conceptual interest, not because I need it anywhere.)

(PS:这个问题仅仅是出于概念上的兴趣,不是因为我在任何地方都需要它。)

6 个解决方案

#1


26

Tested and works :)

经过测试和工作:)

$array = array( "a" => "1", "b" => "2", "c" => "3" );

function replace_key($array, $old_key, $new_key) {
    $keys = array_keys($array);
    if (false === $index = array_search($old_key, $keys)) {
        throw new Exception(sprintf('Key "%s" does not exit', $old_key));
    }
    $keys[$index] = $new_key;
    return array_combine($keys, array_values($array));
}

$new_array = replace_key($array, "b", "e");

更多相关文章

  1. php吧字符串直接转换成数组处理
  2. 使用 PHP usort() 通过用户自定义的比较函数对数组进行排序
  3. PHP print_r 转换/还原为数组
  4. 本机PHP函数将授予我直接访问字符串部分而无需创建临时数组的权
  5. 快速使用数组的最近元素来确定新元素是否唯一
  6. 填充PHP数组:首先检查索引?
  7. 如何在php数组中获取php键值
  8. 将SQL查询的SELECT子句解析为PHP数组
  9. PHP不区分大小写数组搜索函数[duplicate]

随机推荐

  1. React组件的属性PropTypes
  2. 用户打开一个DropDown关闭其他DropDowns
  3. 无法从按钮onclick事件ASP.NET 4调用Java
  4. 从动态生成的音频标签中收听audio.ended
  5. 获取当前时间getDate()注意点
  6. 使用Angularjs根据值选择复选框
  7. 通过IE中的DOM访问帧
  8. 一张图轻松搞懂javascript event对象的cl
  9. 使用jackson json将属性添加到json字符串
  10. 如何.abort()ajax文件上传?