tags:

views:

37

answers:

2

I have two arrays:

array (
 'AK_AGE_ASS_VISIBLE' => '1',
 'AK_AGE_ASS_COMP' => '0',
  .....
 )

I want to change the key to another value taking it from another array:

array(
'AK_AGE_ASS_VISIBLE' => 'AGENT_ASSOCIATED',
'AK_AGE_ASS_COMP' => 'AGENT_ASSOCIATED_O',
....
)

The ending array should produce this array:

array(
'AGENT_ASSOCIATED' => '1',
'AGENT_ASSOCIATED_O' => '0',
...
)

What is the correct way to do these kind of things? Please note that the arrayys won't have the same number of entries and there is no warranty that the first array will have a corresponding key in the other array.

Thank you very much

+4  A: 

Try this:

$values = array(
    'AK_AGE_ASS_VISIBLE' => '1',
    'AK_AGE_ASS_COMP' => '0',
    // …
);
$keymap = array(
    'AK_AGE_ASS_VISIBLE' => 'AGENT_ASSOCIATED',
    'AK_AGE_ASS_COMP' => 'AGENT_ASSOCIATED_O',
    // …
);

$output = array();
foreach ($values as $key => $val) {
    $output[$keymap[$key]] = $val;
}
Gumbo
This kills every missing key if it doesn't have a correspondence with $keymap. This is my solution:if ($keymap[$key]) { $output[$keymap[$key]] = $val; } else { $output[$key] = $val; }
0plus1
@0plus1: Use `isset` for the variable existence test: `if (isset($keymap[$key]))`.
Gumbo
+2  A: 

Use built-in array_combine()? http://www.php.net/manual/en/function.array-combine.php

You probably need to use array_intersect_key() to filter out those keys that don't exist in either on of the arrays. http://www.php.net/manual/en/function.array-intersect-key.php

Here is a magical one-liner:

$output = array_combine(
   array_intersect_key($array_with_keys, $array_with_values),
   array_intersect_key($array_with_values, $array_with_keys));
Lukman
While being correct, this effectively kills every $array_with_values that don't have a corresponding key in $array_with_keys. Anyway thank you, you made me learn something new!
0plus1
you didn't mention what we should do with keys that don't exist in either one so I assumed we are to ignore them.
Lukman
anyway, i can easily modified the one-liner to cater your requirement **if** you have made it clear in the question ... but meh whatever.
Lukman