问题
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