I have created a function that takes two arguments, an array of users and an array of mapping attributes.
They look like this:
$users = [
[
"givenName" => "John",
"surname" => "Doe"
]
]
$mappingAttributes = [
"firstName" => "givenName",
"lastName" => "surname"
]
I want to use $mappingAttributes as a map to replace the keys in $users with the keys in $mappingAttributes.
Desired Output
$users = [
[
"firstName" => "John",
"lastName" => "Doe"
]
]
The function I created, which does the job, looks like this:
function mapAttributes(array $users, array $mappingAttributes): array
{
$mappedUsers = [];
foreach($users as $user) {
foreach($user as $userAttributeKey => $userAttributeValue) {
$newKey = array_search($userAttributeKey, $mappingAttributes);
if($newKey != 0) {
$user[$newKey] = $user[$userAttributeKey];
unset($user[$userAttributeKey]);
}
}
array_push($mappedUsers, $user);
}
return $mappedUsers;
}
This works, however, I feel like there must be a more optimal way to do this, any input would be greatly appreciated.
Thanks!
2
Answers
I think the only optimization you can do is to create the map for keys to be replaced instead of using
array_search
all the time. For this, you canarray_flip
your mapping array and now instantly you have a map at your disposal.Online Demo
The main thing is that you loop through all of the user fields, if instead you loop through the mapping fields, you only alter the ones that will change.
So….
this also updates the array in place (using
&$user
) rather than create a new array.