Access array variable in session (CodeIgniter)

吃可爱长大的小学妹 提交于 2020-01-22 12:02:26

问题


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\']'); 


来源:https://stackoverflow.com/questions/4760848/access-array-variable-in-session-codeigniter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!