开发者

What is the best way to change the key of an array using values from another array?

开发者 https://www.devze.com 2022-12-11 10:30 出处:网络
I have two arrays: array ( \'AK_AGE_ASS_VISIBLE\' => \'1\', \'AK_AGE_ASS_COMP\' =开发者_如何学运维> \'0\',

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));
0

精彩评论

暂无评论...
验证码 换一张
取 消