在Yii2中设置会话变量时遇到问题


Having trouble unsetting session variable in Yii2

我正在使用Yii2,我刚刚开始在其中使用sessions。我已经在Yii网站上阅读了它们的文档。

我注意到的一件事是,如果不使用标准的超全局$_SESSION,在会话中使用多维数组有点困难,因此我主要使用它。

有一件事我有麻烦做虽然是取消会话变量。

的例子:

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']);

使用unset对它根本不起作用,它仍然存在。但是,将其设置为空白值也可以。

试试这个…

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

终于有了一个可行的解决方案,希望这对其他人有所帮助:

$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;