更改数组键而不更改顺序 [英] Change array key without changing order

查看:34
本文介绍了更改数组键而不更改顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以改变"数组元素的键只需设置新键并删除旧键即可:

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:这个问题只是出于概念上的兴趣,不是因为我在任何地方都需要它.)

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

推荐答案

已测试并有效 :)

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

$array = [ 'a' => '1', 'b' => '2', 'c' => '3' ];    
$new_array = replace_key($array, 'b', 'e');

这篇关于更改数组键而不更改顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆