phparraysmappingtranslationassociative-array

Replace keys of an associative array using another associative array


There is a given array and array to map on. What I try to get is if the keys from given is like the key from map I would like the key from given to become the value from map.

Example: the given array looks like this:

given array (size=2)
  'status' => string '200' (length=3)       ------------
  'user' => string 'roger' (length=5)       --------    |
                                                    |   |
                                                    |   |
                                                    |   |
map array (size=6)                                  |   |
  'date' => string 'date' (length=4)                |   |
  'user' => string 'username' (length=8)    --------    |
  'status' => string 'response_code' (length=13)   -----
  'url' => string 'url' (length=3)
  'method' => string 'method' (length=6)
  'ip' => string 'remote_address' (length=14)


desired_result array (size=2)
    'response_code' => string '200' (length=3)
    'username' => string 'roger' (length=5)

See how status (from given array) becomes response_code and user becomes username


Solution

  • You can try the following code

    $given_array = [
        'status'    => '200',
        'user'      => 'roger' 
    ];
    
    $map_array = [
        'date' => 'date',
        'user' => 'username',
        'status' => 'response_code',
        'url' => 'url',
        'method' => 'method',
        'ip' => 'remote_address'
    
    ];
    
    $desired_array = [];
    
    foreach($map_array as $key => $value)
    {
        if(array_key_exists($key, $given_array))
        {
            $desired_array[$value] = $given_array[$key];
        }   
    }
    return $desired_array;