简体   繁体   中英

Delete an array value by another array

Okay, I really don't have any idea on how to explain this.

I have a session array:

$_SESSION['users']['currentuser']['username'] = 'stijn';

this array is build dynamically. So, i need to remove some values of this array also dynamically.

for this, I have a function:

function removeSessionValue($keys) {
                $keys = explode(':', $keys);
                var_dump(array_keys($_SESSION));
                $tempArray = array();
                $reference = &$tempArray;
                foreach ($keys as $key) {
                    $reference[$key] = array();
                    $reference = &$reference[$key];
                }
                $multiArray = $tempArray;
            }

function call= removeSessionValues('users:currentuser:username');

So now I have the originarray (session) and the array to check if the session exists (built by the function).

Is there any way, on how I can unset the $_SESSION['user']['currentuser']['username'] ?

Important note, we don't know what values will be passed in the function, as also we don't know what sessions exists, as everything is ultradynamic ...

A simple way is use eval() :

function deepUnset(&$array, $keys)
{
    $cmd = 'unset($array["'.implode($keys, '"]["').'"]);';
    eval($cmd);
}

// Example:
$_session = array(
    'users' => array(
        'currentUser' => array(
            'username' => 'stijn',
        ),      

        'otherUser' => array(
            'username' => 'james',
        ),
    )
);

echo '<pre>';
print_r($_session);
deepUnset($_session, array('users', 'currentUser', 'username'));
print_r($_session);
echo '</pre>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM