skip to Main Content

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


  1. 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 can array_flip your mapping array and now instantly you have a map at your disposal.

    <?php
    
    function mapAttributes(array $users, array $mappingAttributes): array{
        $mappingAttributes = array_flip($mappingAttributes);
        foreach($users as &$v){
            foreach($v as $key => $value){
                $v[ $mappingAttributes[$key] ] = $value;
                unset($v[ $key ]);
            }
        }
        return $users;
    }
    

    Online Demo

    Login or Signup to reply.
  2. 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….

     function mapAttributes(array $users, array $mappingAttributes): array
        {
            foreach($users as &$user) {
                foreach($mappingAttributes as $newKey => $oldKey) {
                    if (isset($user[$oldKey]))  {
                        $user[$newKey] = $user[$oldKey];
                        unset($user[$oldKey]);
                    }
                }
            }
            return $users;
        }
    

    this also updates the array in place (using &$user) rather than create a new array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search