In PHP, how do you change the key of an array element?

后端 未结 23 2635
逝去的感伤
逝去的感伤 2020-11-22 03:45

I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an I

23条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 04:17

    The way you would do this and preserve the ordering of the array is by putting the array keys into a separate array, find and replace the key in that array and then combine it back with the values.

    Here is a function that does just that:

    function change_key( $array, $old_key, $new_key ) {
    
        if( ! array_key_exists( $old_key, $array ) )
            return $array;
    
        $keys = array_keys( $array );
        $keys[ array_search( $old_key, $keys ) ] = $new_key;
    
        return array_combine( $keys, $array );
    }
    

提交回复
热议问题