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

后端 未结 23 2363
逝去的感伤
逝去的感伤 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:21

    Easy stuff:

    this function will accept the target $hash and $replacements is also a hash containing newkey=>oldkey associations.

    This function will preserve original order, but could be problematic for very large (like above 10k records) arrays regarding performance & memory.

    function keyRename(array $hash, array $replacements) {
        $new=array();
        foreach($hash as $k=>$v)
        {
            if($ok=array_search($k,$replacements))
                $k=$ok;
            $new[$k]=$v;
        }
        return $new;    
    }
    

    this alternative function would do the same, with far better performance & memory usage, at the cost of loosing original order (which should not be a problem since it is hashtable!)

    function keyRename(array $hash, array $replacements) {
    
        foreach($hash as $k=>$v)
            if($ok=array_search($k,$replacements))
            {
              $hash[$ok]=$v;
              unset($hash[$k]);
            }
    
        return $hash;       
    }
    

提交回复
热议问题