This is made more complicated by the possibility that there are elements in the original array that don't need their keys remapped.
function remap_array_keys($mapping, $input)
{
// Because the keys of an associative array aren't necessarily in a particular order
ksort($mapping);
ksort($input);
// Could probably be simplified if there was a guaranteed 1:1
// mapping between the elements of the two arrays
// (there wouldn't be this need to filter keys that appear in one array but not the other)
$matched_values = array_intersect_key($input, $mapping);
$matched_keys = array_intersect_key($mapping, $input);
$unmatched_values = array_diff_key($input, $matched_values);
$remapped_values = array_combine($matched_keys, $matched_values);
return $remapped_values + $unmatched_values;
}
Since the same mapping is probably used for multiple arrays, it's boring to pass it every time when one can create a function on the fly customised for each mapping.
function remap_array_keys($mapping)
{
ksort($mapping);
return function($input)use($mapping)
{
// Because the keys of an associative array aren't necessarily in a particular order
ksort($input);
// Could probably be simplified if there was a guaranteed 1:1
// mapping between the elements of the two arrays
$matched_values = array_intersect_key($input, $mapping);
$matched_keys = array_intersect_key($mapping, $input);
$unmatched_values = array_diff_key($input, $matched_values);
$remapped_values = array_combine($matched_keys, $matched_values);
return $remapped_values + $unmatched_values;
};
}
$map_person_info = remap_array_keys(array(
'name' => 'Full Name',
'address' => 'Place of Residence',
'city' => 'City of Residence',
'job' => 'Professional Career',
'dob' => 'Date of Birth',
'notused' => 'fnord',
));
$a = array('name' => 'john doe', 'address' => '555 Timbuktu Drive', 'city' => 'Los Angeles', 'job' => 'mechanic', 'dob' => '4/30/1943', 'something'=>'else');
$c = $map_person_info($a);
print_r($c);