更改数组键而不更改顺序
16lz
2021-01-22
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");
更多相关文章
- php吧字符串直接转换成数组处理
- 使用 PHP usort() 通过用户自定义的比较函数对数组进行排序
- PHP print_r 转换/还原为数组
- 本机PHP函数将授予我直接访问字符串部分而无需创建临时数组的权
- 快速使用数组的最近元素来确定新元素是否唯一
- 填充PHP数组:首先检查索引?
- 如何在php数组中获取php键值
- 将SQL查询的SELECT子句解析为PHP数组
- PHP不区分大小写数组搜索函数[duplicate]