php CodeIgniter 将会话变量添加到已定义的“命名会话”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16010640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CodeIgniter adding session variable to an already defined "named session"
提问by user2247377
I already created as session named "verified" as shown below (in my login controller):
我已经创建了名为“已验证”的会话,如下所示(在我的登录控制器中):
foreach($result as $row)
{
$sess_array = array(
'id' => $row->memberid, //Session field: id.
'username' => $row->member_userunique //Session field: username.
);
// Create a session with a name verified, with the content from the array above.
$this->session->set_userdata('verified', $sess_array);
}
Now, when a user open a page called book (with a controller named book) i want to add one more additional variable called "book_id" to my "verified" session.
现在,当用户打开名为 book 的页面(带有名为 book 的控制器)时,我想向我的“已验证”会话添加一个名为“book_id”的额外变量。
This is what i have done
这就是我所做的
function index()
{
//Add a new varible called book_id
$this->session->set_userdata('book_id', $titleID);
}
When i tried to retrieve the 'book_id' using the following method:
当我尝试使用以下方法检索“book_id”时:
$session_data = $this->session->userdata('verified');
$article_id = $session_data['book_id'];
$user_id = $session_data['id'];
It only able to retrieve the 'id' however the 'book_id' is not defined. But if do a var_dump() on $this->session->all_userdata() i can see that the 'book_id' session variable has been successfully appended.
它只能检索“id”,但未定义“book_id”。但是,如果在 $this->session->all_userdata() 上执行 var_dump() 我可以看到“book_id”会话变量已成功附加。
After reading the CI documentation about session, i realized that the code above will not work as i have not tell it to which session should i add the variable to.
在阅读了关于 session 的 CI 文档后,我意识到上面的代码将不起作用,因为我没有告诉它我应该将变量添加到哪个会话。
Can anyone point me to the right direction?
任何人都可以指出我正确的方向吗?
回答by tomor
You do as follows in your index()
method:
您在index()
方法中执行以下操作:
$session_data = $this->session->userdata('verified');
$session_data['book_id'] = "something";
$this->session->set_userdata("verified", $session_data);
This way you retrieve the contents of the variable (i.e. the array that you persisted earlier), you add another key to the array (book_id), and then store it again. Now you will be able to do, as I assume you want to:
通过这种方式,您可以检索变量的内容(即您之前保存的数组),将另一个键添加到数组 (book_id),然后再次存储它。现在您将能够做到,正如我假设您想要的那样:
$sess = $this->session->userdata("verified");
echo $sess['book_id'];