What is the best way to change the key of an array using values from another array?
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
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;
}
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));
精彩评论