add value into userdata array

和自甴很熟 提交于 2019-12-25 06:55:16

问题


I thought this would be simple but I cant seem to get it to work. All I want to do is to add a value into a userdata array. If a value is already in the viewed_news_items array I do not want to replace it.

             $data = array(
                'username' => $this->input->post('username'),
                'is_logged_in' => true,
                'viewed_news_items' => array()
            );

            $this->session->set_userdata($data);

insert value into viewed_news_items array

        $a = array($desk_id => $desk_id);
        $this->session->set_userdata('viewed_news_items', $a);

回答1:


You're using $desk_id as both the key and value, meaning unless you already have the value of $desk_id, you won't be able to look it up in the array.

Instead of this:

$a = array($desk_id => $desk_id);

You probably wanted to do this:

$a = array('desk_id' => $desk_id);

That is, use the string 'desk_id' as the key whose corresponding value is $desk_id.


Is there a way to have the 'desk_id' just as an auto number so each time the code is executed another value is added instead of replacing 'desk_id'?

You can push items onto the end of an array via array_push($array, $value) or $array[] = $value. PHP will automatically assign the next numeric ID as the index for the new array element.

In your current scenario, you'll have to pull the existing list of IDs out of the session, append an ID to it, and then put it back into the session:

# pull the existing IDs out of the session
$viewed_news_items =  $this->session->userdata('viewed_news_items');

# on first load, the array may not be initialized
if (!is_array($viewed_news_items))
  $viewed_news_items = array();

# append $desk_id to the list of viewed items
$viewed_news_items[] = $desk_id;

# put the new list back into the session
$this->session->set_userdata('viewed_news_items', $viewed_news_items);



回答2:


invoke the type of data you retrieved from session and use it as you want.

$ID = 123;
$data = (array)$this->session->userdata("session_name");
$data[] = $ID;
$this->session->set_userdata("session_name",$data);


来源:https://stackoverflow.com/questions/9467101/add-value-into-userdata-array

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