开发者

Adding to an array in $_SESSION

I have a survey script that has 3 questions per page. When users answer the questions on the first page and click next, the data from the previous page is stored in $_SESSION['survey']['data'] by doing this:

$data = postToArray($_POST, $ignore_fields);
$_SESSION['survey']['data'] = $data;

$data is an array that looks like:

array('question' => 'answer', 'question' => 'answer');

postToArray does a few checks and manipulates the actual submission a bit, before returning it to $data.

When the user is on page two of the survey, the same thing happens over. I assumed that when $data gets added to the session, via $_SESSION['survey']['data'] = $data;, that it would append to the session array if the 'question' (key) did not exist, but if it did (because the user went to a previous page and changed their answer), that the existing value with the same key would be overwritten, however the last page's submission overwrites everything in the ['data'] array in the session. Come to think about it, that makes perfectly sense.

I tried various things, such as retrieving the $_SESSION['survey']['data'], storing it in array, reading the last submission, merging the arrays, and then re-saving everything in the SESSION, but my code didn't work out -- does this approach make sense? Is that possible?

I also tried array_push, but no luck there.开发者_JAVA百科

In addition, I tried adding to $_SESSION['survey']['data'][], which at least saves everything (each submission in its own array), but then if the user goes back a page, any values they change and re-submit are added as another array.

Preferably, I'd like one giant array with all questions/answers and it keeps adding to that array and overwrites any values with existing keys.

What's the best approach?

Thanks, -Ryan

SOLUTION IMPLEMENTED

$data = postToArray($_POST, $ignore_fields);
foreach($data as $question => $answer)
{
    $_SESSION['survey']['data'][$question] = $answer;
}


Try to serialize the data before saving it in a session variable.

http://php.net/manual/en/function.serialize.php


Loop through the $data array and set it up as naiquevin stated, $_SESSION['survey']['data'][$data['question']] = $data['answer'].


 <?php
  session_start();
  if(!isset($_POST["submit"])){
  $_SESSION["abc"]=array("C", "C++","JAVA","C#","PHP");
  }

   if(isset($_POST["submit"])){
   $aa=$_POST['text1'];

   array_push( $_SESSION["abc"],$aa);
   echo "hello";
    foreach( $_SESSION["abc"] as $key=>$val)
    { 

        echo $val;
    }
  }

?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜