创建并传输数组php


Create and transfert array php

我正在寻找一种从表单创建数组并将其转移到另一个页面的方法:这是我的实际代码:

    <?php
$nba = $_GET["nbadultes"]; // recup number of passangers
$adu = array();
for ($i=1;$i<=$nba;$i++)
{
    echo '<h3>Passager '.$i.'</h3>
        <label>CIVILITÉ</label>
            <select class="full-width" name="Civilite">
                <option value="Mr" selected >Mr.</option>
                <option value="Mrs" >Mrs.</option>
            </select>
        <label>FIRSTNAME *</label>
        <input type="text" name="FIRSTNAME"/>
        <label>LASTNAME *</label>
        <input type="text" name="LASTNAME"/> ';
    $adu[$i][civilite] = $_POST['civilite'];
    $adu[$i][FIRSTNAME] = $_POST['FIRSTNAME'];
    $adu[$i][LASTNAME] = $_POST['LASTNAME'];
}
$_SESSION['liste_adultes'] =$adu; 
?>

并且这个代码在下一页读取数组:

        <?php 
        if (isset($_SESSION['liste_adultes'])) 
        print_r ($liste_adultes);
        ?>

但我不知道为什么数组是空的:

Array
(
[1] => Array
    (
        [Civilite] => 
        [FIRSTNAME ] => 
        [LASTNAME] => 
    )
[2] => Array
    (
        [Civilite] => 
        [FIRSTNAME ] => 
        [LASTNAME] => 
    )
)
  1. 你需要注意你发送的表单输入
  2. 正如我所看到的,现在表单还没有提交,所以你不需要会话,而是需要一个将操作设置为处理发送数据的页面的表单。类似于:

    <form method="post" action="my-action-file.php">
    <?php
    $nba = $_GET["nbadultes"];
    for ($i = 1; $i <= $nba; $i++) {
        echo '<h3>Passager '.$i.'</h3>
            <label>CIVILITÉ</label>
                <select class="full-width" name="Civilite[]">
                    <option value="Mr" selected >Mr.</option>
                    <option value="Mrs" >Mrs.</option>
                </select>
            <label>FIRSTNAME *</label>
            <input type="text" name="FIRSTNAME[]"/>
            <label>LASTNAME *</label>
            <input type="text" name="LASTNAME[]"/> ';
    }
    ?>
       <input type="submit" value="Submit" />
    </form>
    

my-action-file.php文件中,您可以将$_POST变量获取为:

<?php
   foreach ($_POST['Civilite'] as $key => $civilite) {
       $firstName = $_POST['FIRSTNAME'][$key];
       $lastName = $_POST['LASTNAME'][$key];
       // now you have the sent data.. just use it like you need..
   }
   // of course you can add these data to an array if you like so

在第二页中,您需要读取会话数据,然后将您在会话中保存的特定值读取到您使用的变量中:

<?php 
    if(!isset($_SESSION)){ session_start();}
    if(isset($_SESSION['liste_adultes'])){
       $liste_adultes = $_SESSION['liste_adultes'];
       print_r($liste_adultes);
    }
?>

此外,在第一页中,确保发布数据并使用$_post;或通过带有$_GET 的查询字符串