【问题标题】:Having trouble unsetting session variable in Yii2在 Yii2 中取消设置会话变量时遇到问题
【发布时间】:2015-10-22 02:53:25
【问题描述】:

我正在使用Yii2,我刚刚开始在其中使用sessions。我已经在 Yii 网站上为他们阅读了documentation

我注意到的一件事是,如果不使用标准的超全局 $_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 根本不起作用,它仍然存在。但是,将其设置为空白值是可行的。

【问题讨论】:

    标签: php session yii yii2 unset


    【解决方案1】:

    试试这个..

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

    可以帮助你..

    【讨论】:

    • 是的,我知道你可以做到这一点,但是如何删除 multi-dimensional 数组中的值?这只会删除整个$_SESSION['foo']
    • 试试foreach ($session as $name => $value) { $session->remove('$value); }
    • 那也行不通; remove 只能在第一级移除。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2010-11-04
      • 2013-12-19
      • 2016-10-01
      • 2013-02-17
      • 1970-01-01
      • 2022-11-01
      • 2017-09-12
      • 2015-03-03
      相关资源
      最近更新 更多