Change array key without changing order

前端 未结 8 1595
难免孤独
难免孤独 2020-12-03 07:17

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]);         


        
8条回答
  •  暖寄归人
    2020-12-03 07:58

    One way would be to simply use a foreach iterating over the array and copying it to a new array, changing the key conditionally while iterating, e.g. if $key === 'foo' then dont use foo but bar:

    function array_key_rename($array, $oldKey, $newKey) 
    {
        $newArray = [];
        foreach ($array as $key => $value) {
            $newArray[$key === $oldKey ? $newKey : $key] = $value;
        }
        return $newArray;
    }
    

    Another way would be to serialize the array, str_replace the serialized key and then unserialize back into an array again. That isnt particular elegant though and likely error prone, especially when you dont only have scalars or multidimensional arrays.

    A third way - my favorite - would be you writing array_key_rename in C and proposing it for the PHP core ;)

提交回复
热议问题