Unsetting an inner element of an array attached to a session when using CodeIgniters' Database Sessions
I have two questions. Both involve CodeIgniter's session support when using the database as a backend.
1. I'm wondering if there is a way of unsetting an inner element of an array against a session when using CodeIgniter's Database Session support.
For example, in standard PHP this sort of functionality is possible:
unset($_SESSION['items'][$item_name]);
However, CodeIgniter seems to work like this:
$this->session->unset_userdata('items'); // What about unsetting $item_name specifically?
2. And I'm not sure the best way of unsetting an individual array item.
The other thing I would like to be able to do is to check whether an inner element of a开发者_StackOverflow社区n array is set.
For example, in standard PHP this sort of functionality is possible:
if (isset($_SESSION['items'][$item_name])) {
}
But in CodeIgniter we have something like this:
if ($this->session->userdata('items') !== FALSE) {
}
The equivalent to $_SESSION
in Codeigniter is
$this->session->userdata
This might look like the same named function name
$this->session->userdata();
to you, but in fact it's an array, like $_SESSION
. With this information, let's look at your specific questions:
# 1. unset an item:
unset($this->session->userdata['items'][$item_name]);
# 2. check if an item is set:
if (isset($this->session->userdata['items'][$item_name])) {
}
If you would like to access that more easily, you can create a reference/alias:
$session =& $this->session->userdata;
unset($session['items'][$item_name];
if (isset($session['items'][$item_name])) {
}
To apply the changes to the session variable(s), you need to call
$this->session->sess_write();
to store the values into the database. That's better than using the userdata()
function, because it will trigger a write in the database whenever you set a single value.
精彩评论