$ _POST数据到$ _SESSION数组

时间:2016-07-04 22:55:11

标签: php arrays forms

我有一个表单,允许用户输入姓名和相关的出生日期。

该表单允许用户动态添加更多姓名和出生日期。

我想将此数据推送到关联的数组$ _SESSION变量,然后循环遍历它。

<form action="page.php">
  <input type="text" name="child[0][name]" value="Name">
  <input type="text" name="child[0][dob]" value="Date of Birth">
  <input type="submit" value="Submit">
</form>

//trying to save the posted data to a SESSION
$_SESSION['children'] = [];

if (isset($_POST['child'])) {
    foreach ($_POST['child'] as $value) {
       array_push($_SESSION['children'], $value['name']);
       array_push($_SESSION['children'], $value['dob']);
    }
}

SESSION的循环会让我的数据变为什么:

Peter Smith born on 11/11/1900
Sally Smith born on 11/22/2222

当我print_r($ _ SESSION)时:

Array ( [0] => Peter Smith [1] => 11/11/1900 [2] => Sally Smith [3] => 11/22/2222 )

2 个答案:

答案 0 :(得分:1)

对于您当前的会话价值,您可以这样:

$for($i=0; $i<count($_SESSION['children']); $i+=2){
    echo $_SESSION['children'][$i] . ' born on ' . $_SESSION['children'][$i+1] . '<br>';
}

如果您只是保留密钥以获得更精确的代码,那会更好。看看:

// .. code ..
if (isset($_POST['child'])) {
    // check if it's not created yet
    if(!isset($_SESSION['children']){
        $_SESSION['children'] = array();
    }
    // Adds (without replacing) the values from post to session
    $_SESSION['children'] = array_merge($_SESSION['children'], $_POST['child']);
    // Display the new session data
    foreach($_SESSION['children'] as $v){
        // better access using "name" and "dob"'s keys
        echo $v['name'] . ' was born on ' . $v['dob'] . '<br>';
    }
}

请注意,此代码保留以前的$_SESSION['children']值。

答案 1 :(得分:0)

首先,如果它不是数组

,则仅初始化$_SESSION['children']
if (!array_key_exists('children', $_SESSION)) {
    $_SESSION['children'] = [];
}

然后,只需将$_POST合并到$_SESSION['children']

即可
$_SESSION['children'] = array_merge($_SESSION['children'], $_POST);