How Can I Save A Session Array?

Hi,

How can I save a session array in Yii 2.0?

I tried do in this way:


public function actionSession()

        {

             if (null !== \Yii::$app->request->post('id') && \Yii::$app->request->post('id') > '0') {

                 

                 $savedTip = [\Yii::$app->request->post('id') => \Yii::$app->request->post('tip')];

                 

                 \Yii::$app->session['tippIds'][] = $savedTip; // This is the 127th line, the problem is here.

             }

             //print_r(json_encode($savedTip));

             return json_encode(\Yii::$app->session['tippIds']);

        }



And I got this problem in:




exception 'yii\base\ErrorException' with message 'Indirect modification of overloaded element of yii\web\Session has no effect' in /var/www/html/tipp/controllers/BettingController.php:127

Stack trace:

#0 /var/www/html/tipp/vendor/yiisoft/yii2/base/InlineAction.php(53): ::call_user_func_array()

#1 /var/www/html/tipp/vendor/yiisoft/yii2/base/Controller.php(128): yii\base\InlineAction->runWithParams()

#2 /var/www/html/tipp/vendor/yiisoft/yii2/base/Module.php(586): yii\base\Controller->runAction()

#3 /var/www/html/tipp/vendor/yiisoft/yii2/web/Application.php(85): yii\base\Module->runAction()

#4 /var/www/html/tipp/vendor/yiisoft/yii2/base/Application.php(289): yii\web\Application->handleRequest()

#5 /var/www/html/tipp/web/index.php(11): yii\base\Application->run()

#6 {main}



Should I try this with native PHP?

Ok, we can close this post :). With native PHP it is working perfectly for me :).

\Yii::$app->session is an object actually, so you can try something like


$tippIds = \Yii::$app->session['tippIds'];

$tippIds[] = $savedTip;

\Yii::$app->session['tippIds'] = $tippIds;

Mmm, yes, I think it will be a good idea if the yii team will be able to implement a setter method to storage arrays in the Session instead of this 3 lines solution :). (The native 1 line solution is more comfortable for me)

Like this? (Session.php):


/**

 * Adds a session variable.

 * If the specified name already exists, the old value will be overwritten.

 * @param string $key session variable name

 * @param mixed $value session variable value

 */

public function set($key, $value)

{

	$_SESSION[$key] = $value;

}

How about this,


\Yii::$app->session['tippIds'] = array_merge(\Yii::$app->session['tippIds'], [$savedTip]);