Access array variable in session (CodeIgniter)

2019-03-18 16:37发布

问题:

I have an array called config. I'm trying to echo a variable from the array in the session.

I've tried:

echo $this->session->userdata('config['item']'); 

but it doesn't work. What's wrong with my syntax here? I've print_r'd my session and the items are in the config array. I've also tried:

echo $this->session->userdata("config['item']");

I get no errors this time, but no data either.

回答1:

If config is an array . And item is string name of what you want to get from config then

echo $this->session->userdata($config['item']);

or

echo $_SESSION[$config['item']];

If config is an array inside session you should first get it.

$tmp = $this->session->userdata('config');
echo $tmp['item'];

or

echo $_SESSION['config']['item'] 

Sorry for my english.



回答2:

If you want to use the session array, use the variable, not the function:

echo $this->session->userdata['user_data']['item'];

If you want to write:

$this->session->userdata['user_data']['item'] = 'value';
$this->session->userdata['other_data']['other'] = 'value2';
$this->session->sess_write();

This allows you to edit values in array just like you do with $_SESION['user_data']['avatar'] = $avatar, with 'only' one extra line and only using CI library.



回答3:

Always escape your string it should be this way:

echo $this->session->userdata('config[\'item\']'); 


标签: codeigniter