在会话中存储数组

时间:2013-12-16 06:14:41

标签: php session yii

我试图将一些数据作为数组存储在会话中,但该函数似乎没有工作。它不会抛出任何错误,但每次我向其添加数据时,它只会覆盖以前的数据。我正在使用yii,这是行动

public function actionStoreProducts($name)
        {
            $name=trim(strip_tags($name));
            if(!empty($name))
            {
                if(!isset(Yii::app()->session['_products']))
                {
                    Yii::app()->session['_products']=array($name);  
                    echo 'added';
            }
            else
            {

                $myProducts = Yii::app()->session['_products'];
                $myProducts[] = $name;
                Yii::app()->session['products'] = $myProducts;
                echo 'added';

            }

        }

任何人都可以建议我如何才能达到预期效果?

3 个答案:

答案 0 :(得分:3)

请更正您的代码。

public function actionStoreProducts($name) {
        $name = trim(strip_tags($name));
        if (!empty($name)) {
            if (!isset(Yii::app()->session['_products'])) {
                Yii::app()->session['_products'] = array($name);
                echo 'added';
            } else {

                $myProducts = Yii::app()->session['_products'];
                $myProducts[] = $name;
                Yii::app()->session['_products'] = $myProducts;
                echo print_r(Yii::app()->session['_products']);
                echo 'added';
            }
        }
    }

答案 1 :(得分:2)

会话属性只读 我认为正确的方法是:

function actionStoreProducts($name) {
    $session = new CHttpSession;               //add this line
    $session->open();                          //add this line
    $name = trim(strip_tags($name));
    if (!empty($name)) {
        if (!isset(Yii::app()->session['_products'])) {
            $session->add('_products', array($name));   //replace this line
            echo 'added';
        } else {

            $myProducts = Yii::app()->session['_products'];
            $myProducts[] = $name;
            $session->add('_products', $myProducts);    //replace this line
            echo 'added';
        }
    }
}

答案 2 :(得分:2)

首先将变量放入$ session ['somevalue'],然后在数组变量中使用,使用像IT一样: -

    $session = new CHttpSession;
    $session->open();

    $myval = $session['somevalue'];
    $myval[] = $_POST['level'];
    $session['somevalue'] = $myval;