如何在codeigniter中设置会话中的数组?

时间:2013-10-14 19:13:55

标签: php arrays codeigniter

我在会话中设置数组时有点挣扎。

这是我的代码: -

控制器:

function taketest(){
    $this->load->model('', '');
    $questions_for_test = $this->session->userdata('questions_for_test');
    $difficulty_level = $this->session->userdata('difficulty_level');
    $question_id = $this->session->userdata('question_id');
    if($question_id==""){
        $question_id = $this->myjcat->returnRandomQuestion($questions_for_test,$difficulty_level);
        $this->session->set_userdata('question_id',$question_id);
    }
    $question_details = $this->myjcat->getQuestion($question_id);
}

型号:

function returnRandomQuestion($questions_for_test, $difficulty_level){
    $question_id = array_rand($questions_for_test[$difficulty_level], 1);
    $used_question=array();
    $used_questions=$questions_for_test[$difficulty_level][$question_id];
    $this->session->set_userdata('used_questions',$used_questions);
    return $questions_for_test[$difficulty_level][$question_id];
}

但是当我打电话时:

$used_questions = $this->session->userdata('used_questions');

在控制器中 在控制器中它不会返回一个数组。它给我存储在其中的最后一个值。

4 个答案:

答案 0 :(得分:3)

我可能会误读事物,但看起来你只存储了一个值。

// this code:
$used_questions=$questions_for_test[$difficulty_level][$question_id];
$this->session->set_userdata('used_questions',$used_questions);

// is the same as this code
$this->session->set_userdata('used_questions',$questions_for_test[$difficulty_level][$question_id]);

你可能正在寻找这个:

// fetch the stored copy first.
$used_questions = $this->session->userdata('used_questions');
if(!is_array($used_questions)) $used_questions = array();
// note the []
$used_questions[] = $questions_for_test[$difficulty_level][$question_id];
$this->session->set_userdata('used_questions',$used_questions);

答案 1 :(得分:1)

您可以在会话数据中设置数组值,如下所示: -

$this->session->set_userdata('used_questions', json_encode($used_questions));

并将数据检索为: -

json_decode($this->session->userdata('used_questions'));

如果您希望将检索到的数组数据作为关联数组: -

json_decode($this->session->userdata('used_questions'), true);

希望它能解决你:)

答案 2 :(得分:0)

问题是$used_questions存储了$questions_for_test[$difficulty_level][$question_id]而不是数组中存储的值。

这样做$this->session->set_userdata('used_questions',$questions_for_test);

答案 3 :(得分:0)

这是因为传递给$ used_questions的数据是一个值。

您可能想要这样做:

array_push($used_questions, $questions_for_test[$difficulty_level][$question_id]);

*追加/向数组添加新值