如何确保我以特定格式获得所有$ _POST数据

时间:2013-10-26 21:14:58

标签: php forms

我有一个带有一些输入的网页。

输入在某些组中,并且都以一种形式存在。

输入可以动态添加到页面,但都遵循命名规则:numberA-numberB-any。 输入也可以从页面中删除。所以最后我可能会有这样的事情:

<form method="POST">
  <input name="3-1-c">

  <input name="8-2-d">
  <input name="8-3[]">
  <input name="8-3[]">

  <input name="17-2-a">
  <input name="17-2-d">
  ... a few or many other inpooots!
</form>

由于numberA(第2,第3和第4个输入,在第8组中),它们被分组

然后在服务器端用PHP;如何创建一个循环来读取numberA排序的所有这些输入(因为我应该为每个numberA及其所有子集执行一些数据库操作)并且不会丢失任何输入。

while (have_groups_of_inputs(?)) { // inputs with same numberA part
  while (have_items_in_this_group(?)) {
    do_the_job();
  }
}
echo 'thanks!';

$ _ POST数据样本:

Array
(
    [itemcount] => 4
    [formid] => 
    [title] => Your info

    [1-title] => First name
    [1-hint] => your name
    [1-eltype] => 1
    [1-1] => Array
        (
            [0] => 
        )

    [3-title] => Last name
    [3-hint] => 
    [3-eltype] => 1
    [3-1] => Array
        (
            [0] => 
        )

    [4-title] => Gender
    [4-hint] => 
    [4-eltype] => 2
    [4-0] => Array
        (
            [0] => Male
            [1] => Female
        )
)

1 个答案:

答案 0 :(得分:1)

您好,您可以遍历$ _POST数组并根据键

存储值
foreach($_POST as $key=>$value){
    $parts = explode('-', $key);
    if(isset($parts[2])){
        $groups[$parts[0]][$parts[1]][$parts[2]] = $value; 
    }else{
        if(!isset( $groups[$parts[0]][$parts[1]])){
              $groups[$parts[0]][$parts[1]] = array();
        }
        $groups[$parts[0]][$parts[1]][] = $value;
    }
}

这应该会产生一个类似于以下

的数组
{
   '3':{
       '1':{
           'c': value_for_3-1-c
       }
   },
   '8':{
       '2':{
           'd': value_for_8-2-d
       },
       '3':[
           value_for_8-3[0],
           value_for_8-3[1],
       ]
   },
   '17':{
        '2':{
            'a': value_for_17-2-a,
            'd': value_for_17-2-d
        }
   }
}

然后如果你想循环第8组中的每个项目

foreach($groups[8] as $b=>$sub){
    foreach($sub as $key=>$value){
        echo $key . ': ' . $value; 
    }
}

会导致:

d: value for 8-2-d
0: value for 8-3[0]
1: value for 8-3[1]