Change array key without changing order

前端 未结 8 1570
难免孤独
难免孤独 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:42

    You could use array_combine. It merges an array for keys and another for values...

    For instance:

    $original_array =('foo'=>'bar','asdf'=>'fdsa');
    $new_keys       = array('abc', 'def');
    $new_array      = array_combine($new_keys, $original_array);
    
    0 讨论(0)
  • 2020-12-03 07:47

    Check keys existence before proceeding… Otherwise the result can be catastrophic if the new key already exists... or unnecessary processing time/memory consumption if the key to be replaced does not exist.

    function array_rename_key( array $array, $old_key, $new_key ) {
        // if $new_key already exists, or if $old_key doesn't exists
        if ( array_key_exists( $new_key, $array ) || ! array_key_exists( $old_key, $array ) ) {
            return $array;
        }
    
        $new_array = [];
        foreach ( $array as $k => $v ) {
            $new_array[ $k === $old_key ? $new_key : $k ] = $v;
        }
    
        return $new_array;
    }
    
    0 讨论(0)
  • 2020-12-03 07:48

    Tested and works :)

    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');
    
    0 讨论(0)
  • 2020-12-03 07:52

    If possible, one can also put the key to change at the end of the array in the moment of creation :

    $array=array('key1'=>'value1','key2'=>'value2','keytochange'=>'value');
    $x=$array['keytochange'];
    unset($array['keytochange']);
    $array['newkey']=$x;
    
    0 讨论(0)
  • 2020-12-03 07:53

    Do a double flip! At least that is all I can think of:

    $array=("foo"=>"bar","asdf"=>"fdsa");
    $array=array_flip($array);
    $array["bar"]=>'newkey';
    $array=array_flip($array);
    
    0 讨论(0)
  • 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 ;)

    0 讨论(0)
提交回复
热议问题