循环形式与foreach和会话

时间:2013-07-18 01:53:31

标签: php arrays forms loops foreach

我有一个带有循环的表单。 这是我的代码:

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">    
<?php
for ($i = 1; $i <= 2; $i++) {
    echo "Numero ";
    echo $i;
    echo "<input type='text' name='number2[$i]' id='number2{$i}' />";   
}

   ?>
   <input type="submit" name="submitbutton" value="Confirm!">
   </form>
   <?php
   print_r( $_POST  );
if(!isset($submitbutton)) {
    if (isset($_POST['number2']) != "") {
        echo "<b>{$_POST['number2']}</b>, !\n";
        $nI = $_POST['number2'];
    } 
}
?>

我得到的输出是:

  

数组([number2] =&gt;数组([1] =&gt; 3 [2] =&gt; 4)[submitbutton] =&gt;确认!)数组,!

我想知道如何将号码放入会话中。

例如Session[1]=3, Session[2]=4

我尝试使用数组和foreach,但我总是遇到错误。

2 个答案:

答案 0 :(得分:2)

你得到什么错误?请注意,isset()仅返回TRUEFALSE,因此isset($_POST['number2'])将永远不会等于空字符串。

答案 1 :(得分:2)

这样的事情对你有用:

<?php
// Start a PHP Session
session_start();
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">    
    <?php
    for ($i = 1; $i <= 2; $i++) {
        echo "Numero ";
        echo $i;
        echo "<input type='text' name='number2[$i]' id='number2{$i}' />";   
    }
    ?>
    <input type="submit" name="submitbutton" value="Confirm!">
</form>
<?php
// If the form was submitted and number2 is an array
if(isset($_POST['submitbutton']) 
        && isset($_POST['number2']) 
        && is_array($_POST['number2'])) {

    // Loop through each posted value and save it to the session
    foreach ($_POST['number2'] as $key => $value) {
        $_SESSION["number2_{$key}"] = $value;
    } 
}
echo "number2_1 = " . $_SESSION["number2_1"] . "<br />";
echo "number2_2 = " . $_SESSION["number2_2"] . "<br />";
?>