如何在PHP中以单一形式循环遍历常见字段集?

时间:2011-05-06 09:01:34

标签: php arrays forms loops

我有一个表单,其中包含多个虚拟字段集。

例如,MyForm:

Name1
Age1
Location1

Name2
Age2
Location2

Name3
Age3
Location3

Submit

如果我允许用​​户在客户端上动态创建更多字段集,我如何遍历设置了name(x)的所有字段集,并使用整数(1,2,3等)为每个组执行类似的操作)作为唯一标识符?

我想指定一次操作,循环遍历,每次根据字段集的数量更改使用的变量。

现在,我正在为3个硬编码的fireldsets手动完成,但它不会扩展:

伪代码:

if($name1 is set) {
do something using $age1 and $location1
}
if($name2 is set) {
do something using $age2 and $location2
}
if($name3 is set) {
do something using $age3 and $location3
}

谢谢!

4 个答案:

答案 0 :(得分:3)

您可以为元素name="name[1]"name="name[2]"等命名。

并在php中执行以下操作:

for($i=1;$i<=count($name);$i++){
// do the stuff.
}

答案 1 :(得分:1)

这样做:

    $maxIndex = 3

    for(var $i=1; $i<=$maxIndex; $i++){
       $name = $_POST["Name$i"];
       $age = $_POST["Age$i"];
       $location = $_POST["Location$i"];
       //do something using $name, $age and $location
    }

希望这会有所帮助。干杯

答案 2 :(得分:0)

您应该为输入字段使用数组。然后,您可以创建任意数量的以下块:

<input name="name[]" />
<input name="age[]" />
<input name="location[]" />

在PHP中,您可以遍历这些参数:

foreach($_POST['name'] as $key => $value) {
    $name = $_POST['name'][$key];
    $age = $_POST['age'][$key];
    $location = $_POST['location'][$key];
}

答案 3 :(得分:0)

您可以在php中使用数组来制作

首先来自fome,你可以使用

<?php
//n is no of records u want at one time
$available = $n;

for($i=1; $i<=$available; $i++){
 ?>

 Name <input type=hidden name="pname<?=$i?>" value=<?=$pid?>>

 Age<input type=text name="age<?=$i?>" />
 Location<input type=text name="age<?=$i?>" />
 <?php


 }
 ?>

以动作形式,您可以使用一次保存这些多个记录

 <?php
$available_count = $n;

for($i=1; $i<=$available_count; $i++){
        $pname = "pname".$i;
        $age = "age".$i; 
        $location = "location".$i; 


        $pname1 = trim($_POST[$pname]);
        $age1 = trim($_POST[$pname]);
        $location1 = trim($_POST[$location]);
  //now you can insert these values into table/views

  }
  ?>

希望你能找到更好的帮助...

相关问题