2

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

这是我的代码:-

控制器:

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

4 回答 4

4

我可能误读了一些东西,但看起来你只存储一个值。

// 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);
于 2013-10-14T19:19:29.487 回答
2

您可以像这样在会话数据中设置数组值:-

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

希望它对你有帮助:)

于 2013-10-14T22:18:38.113 回答
0

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

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

于 2013-10-14T19:24:09.157 回答
0

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

你可能想做这样的事情:

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

*向数组添加/添加新值

于 2013-10-14T19:47:38.380 回答