简体   繁体   中英

Having trouble unsetting session variable in Yii2

I'm using Yii2 and I have just started working with sessions within it. I have read the documentation for them on the Yii site.

One thing I noticed is it is a bit hard to work with multi-dimensional arrays in sessions without using the standard superglobal $_SESSION and hence I have mainly been using that.

One thing I am having trouble doing though is unsetting a session variable.

Example:

if (!Yii::$app->session->isActive) {
    Yii::$app->session->open();
}

print_r($_SESSION['foo']);

if ($this->command == 'sample_action') {

    if (!isset($_SESSION['foo'][$this->some_id][$this->example_id])) {
        $_SESSION['foo'][$this->some_id][$this->example_id] = $this->example_id;
        $result = true;
    }

} elseif ($this->command == 'sample_action_2') {

    if (isset($_SESSION['foo'][$this->some_id][$this->example_id])) {
        unset($_SESSION['foo'][$this->some_id][$this->example_id]);
        //$_SESSION['foo'][$this->some_id][$this->example_id] = ''; // This works
        $result = true;
    }           

}

print_r($_SESSION['foo']);

Using unset on it doesn't work at all, it still remains. Setting it to a blank value works however.

Try this..

$session = Yii::$app->session;
$session->remove('foo');

May help you..

Finally got a working solution, hopefully this helps someone else:

$session = Yii::$app->session;

$foo = $session['foo'];

if ($this->command == 'sample_action') {
    $foo[$this->some_id][$this->example_id] = $this->example_id;
} elseif ($this->command == 'sample_action_2') {
    unset($foo[$this->some_id][$this->example_id]);
}

$session['foo'] = $foo;

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