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

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

    This basic function handles swapping array keys and keeping the array in the original order...

    public function keySwap(array $resource, array $keys)
    {
        $newResource = [];
    
        foreach($resource as $k => $r){
            if(array_key_exists($k,$keys)){
                $newResource[$keys[$k]] = $r;
            }else{
                $newResource[$k] = $r;
            }
        }
    
        return $newResource;
    }
    

    You could then loop through and swap all 'a' keys with 'z' for example...

    $inputs = [
      0 => ['a'=>'1','b'=>'2'],
      1 => ['a'=>'3','b'=>'4']
    ]
    
    $keySwap = ['a'=>'z'];
    
    foreach($inputs as $k=>$i){
        $inputs[$k] = $this->keySwap($i,$keySwap);
    }
    

提交回复
热议问题