2

I have a PHP function $users->getFullUserList('json') that returns a JSON string holding a Userlist of user data which is built from a PHP Array using PHP's json_encode($this->userListArray)

The PHP Array $this->userListArray looks something like this below before being converted into a JSON string...

Array
(
    [user1] => Array
        (
            [id] => 1
            [user_name] => jasondavis
            [first_name] => Jason
            [last_name] => Davis
            [is_admin] => 1
            [email_address] => jasonyrty@tyrtl.com
            [gravatar_id] => 31b64e4876d603ce78e04102c67d6144
        )

    [1702c3d0-df12-2d1b-d964-521becb5e3ad] => Array
        (
            [id] => 1702c3d0-df12-2d1b-d964-521becb5e3ad
            [user_name] => Jeff
            [first_name] => Jeff
            [last_name] => Mosley
            [is_admin] => 1
            [email_address] => fgfgh@rtyrtyre.com
            [gravatar_id] => 5359bf585d11c5c35602f9bf5e66fa5e
        )
)

What I need help with is making my function $users->getFullUserList('json') to allow another parameter to be injected which will be an array of keys which should NOT be part of the final JSON String

For example if I want to generate my JSON string from the PHP Array and have it exclude user email_address and first_name keys from the JSON string.

I do not want to simply remove them from the PHP Array as I will need access to them in PHP later on. I just want the keys in my new passed in array to be excluded from the generated JSON and still remain in the PHP Array.

$excludeKeysFromJson = array(
    'first_name',
    'email_address'
);

$users->getFullUserList('json', $excludeKeysFromJson)

I realize the simple solution would be to clone my $this->userListArray Array and then remove the matching keys from the $excludeKeysFromJson Array and generate the JSON string from the new cloned Array.

I am hoping to find a better performance method that doesn't require cloning my huge userlist array and keeping 2 copies of the userlist array with 1 missing a couple keys.

Is there a better way?

JasonDavis
  • 48,204
  • 100
  • 318
  • 537

1 Answers1

4

You can create an array with keys filtered out using array_diff_key and array_flip (to turn the exclusion array values into keys)

Something like this...

public function getFullUserList($format, array $exclude = []) {
    $filtered = array_map(function($user) use ($exclude) {
        return array_diff_key($user, array_flip($exclude));
    }, $this->userListArray);

    switch($format) {
        case 'json' :
            return json_encode($filtered);
        default :
            return $filtered;
    }
}

Demo

Phil
  • 157,677
  • 23
  • 242
  • 245
  • @JasonDavis there was some inspiration from this post ~ http://stackoverflow.com/questions/4260086/php-how-to-use-array-filter-to-filter-array-keys – Phil Aug 06 '15 at 03:30