更改数组的键不改变秩序 [英] Change array key without changing order

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

问题描述

您可以\"change\"数组元素的只需通过设置新键和删除键的旧:

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.)

推荐答案

测试和工程:)

$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");

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

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