1

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

0

3 Answers 3

3

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;
Sign up to request clarification or add additional context in comments.

Comments

2

I had to fix second argument, because array_combine doesn't check keys (order only), so with different key order it starts getting ugly:

$result = array_combine($mapx = array_intersect_key($map, $given), array_replace($mapx, $given));

1 Comment

thanks for your time and answer! Yes I've seen in the first example after a while that it brakes.. now it starts to get complicated .. but thank you
1

You can simply use array_walk like as

$result = [];
array_walk($given_array,function($v,$k)use(&$result,$map_array){
    $result[$map_array[$k]] = $v;
});
print_r($result);

Output:

Array
(
    [response_code] => 200
    [username] => roger
)

Demo

Or simpler using foreach loop

$result=[];
foreach($given_array as $key => $value){
    $result[$map_array[$key]] = $value;
}
print_r($result);

Demo

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.