如何根据html表单输入设置数组中的项数


How to set the number of items in an array based on html form input?

我正在创建一个PHP文件,我想做的一件事是拥有一个数组(示例1(。据我所知,数组就像一个列表,我也想在列表上输入项目(示例2(。但是数组中项目的数量需要由通过HTML表单输入的数字来确定(示例3(。

示例1:

<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
</body>
</html>
</code>    

示例2:

<!DOCTYPE html>
<html>
<body>
<?php
$a=array("red","green");
array_push($a,"$_POST["color3"]","$_POST["color4"]");
print_r($a);
?>
</body>
</html>

示例3。

<ol>
<form action="finished.php" method="post">
<li><input type="text" name="color3"></li>
<li><input type="text" name="color4"></li>
</form>
</ol>

编辑:我希望这一切都是正确的格式,你理解这个问题。重申一下:第一页是空白的,只有一张表格;单个输入框,您可以在其中键入任意数字(X(。第二页的同一行重复出现(取决于前一页的数字X(,其行为:<li><input type="text" name="color Y"></li>
Y应该从1开始无限计数,直到达到X为止。"最后一页"将所有内容打印到列表中(数组?(。

例如:在第一页上,我们输入数字3。在第二页上,我们有3个框用于输入我们选择的颜色的名称:红色、蓝色、黄色。在最后一页上,我们看到了三种颜色的列表:红色、蓝色和黄色。

希望这能有所帮助。

<ol>
<form action="finished.php" method="post">
<li><input type="text" name="data['color3']"></li>
<li><input type="text" name="data['color4']"></li>
</form>
</ol>

然后在finished.php 中

 $_POST['data'];
  print_r($_POST);//print out the whole post
  print_r($_POST['data']); //print out only the data array

我想我得到了你想要的(在读了不止一次之后(。如果我理解正确,请告诉我。假设您使用了3个不同的文件(正如您在问题中所写的(。

file1.php(一个有1个输入和1个提交按钮的简单表单(:

<form action="file2.php" method="post">
    <input type="text" name="amount" placeholder="The amount of elements">
    <input type="submit" value="Enter">
</form>

file2.php(检查$_POST和值是否为整数(:

if (!empty($_POST['amount'])) {
    if (!is_int($_POST['amount'])) {
        exit('Not an integer');
    }
    ?>
    <form action="file3.php" method="post">
    <?php
    for ($i = 0; $i < $_POST['amount']; $i++) {
        echo '<input type="text" name="colors[]" placeholder="Enter color name"><br>';
    }
    ?>
    <input type="submit" value="Done">
    </form>
    <?php
} else {
    exit('Only $_POST method is allowed.');
}

file3.php(获取所有结果并将数组存储在变量中(:

if (!empty($_POST)) {
    $colors = $_POST['colors'];
    foreach ($colors as $color => $value) {
        echo '<li>'.$value.'</li>';
    }
    exit;
} else {
    exit('Only $_POST method is allowed.');
}

我们可以添加更多的安全性(比如检查它是否为空等(,但我只添加了一些基本的东西。