开发者

how do i reset the value of a single session array index in codeigniter?

Using a user model which returns an array that looks like this:

$user_data['display_name'] = "John Doe";

$user_data['avatar'] = ./images/user144.jpg";

i create my session using $this->session->set_userdata('user_data',$user_data);

now if on another controller i let the 开发者_如何转开发user change his avatar,

how can i replace the session variable associated to that?

like $this->session->set_userdata('user_data["avatar"]',$new_avatar); just wont work right?

hee thanks for the help...


From looking at an overview of your code, I'm guessing the best way to go about this is to unset the data and reset it.

Use $this->session->unset_userdata('thesessiontounset'); Then set it back up with the new information and old.


The session->set_userdata() function will only let you modify one key at a time. In your case the key refers to an array so what you're trying to do isn't possible in the way you're attempting to do it.

When I'm updating my session I run something like this.

//Create or setup the array of the fields you want to update.
$newFields = array('avatar' = > 'image01.png');

//Check to see if the session is currently populated. 
if (!is_array($this->session->userdata('abc'))){
    //...and if it's not - set it to a blank array
    $this->session->set_userdata('abc',array());
}

//Retrieve the existing session data
$existing_session = $this->session->userdata('abc');

//Merge the existing data with the new data
$combined_data = array_merge($this->session->userdata('abc'), $newFields);
//update the session
$this->session->set_userdata('abc',$combined_data);

More details on array_merge can be found here


First controller

$user_data['display_name'] = "John Doe";

$user_data['avatar'] = "./images/user144.jpg";

$this->session->set_userdata('user_data',$user_data);

Second controller

$user_data = $this->session->userdata('user_data');

$user_data['avatar'] = $new_avatar;

$this->session->set_userdata('user_data', $new_avatar);


It is a bit late, but it might be useful to someone else, this seems to work:

$this->session->userdata['user_data']['avatar'] = $new_avatar;
$this->session->userdata['other_data']['other'] = $other;
$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.


For Unset Session variable

$this->session->unset_userdata('avatar');   

For Set Session variable

$this->session->set_userdata('avatar', '/images/user144.jpg"');


Use just like this

$this->session->set_userdata('session_var',"");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜