将元素表单转换为$ _POST数组

时间:2012-06-22 15:32:41

标签: html forms

我可能是愚蠢的,因为它是星期五下午,但我无法解决这个问题。

我想要的是一个用户可以添加无限“记录”的表单。为此,他们单击“添加记录”按钮。这会运行javascript,它会在<form>

中的表中添加一个新行(tr)

这个新行有三个输入字段。

我想要的是以一种格式将其发送到post变量(但如果无法完成则不准确,但有更好的方法):

$_POST['record'] = array(
    array(
        "input1" => "value",
        "input2" => "value",
        "input3" => "value"
    ),
    array(
        "input1" => "value",
        "input2" => "value",
        "input3" => "value"
    ),
    array(
        "input1" => "value",
        "input2" => "value",
        "input3" => "value"
    ),
);

我知道您可以使用如下名称来获取数组:

<input type="text" name="record[]" />

但这只是一个输入元素。有没有办法让上面的结构有3个元素?

谢谢。

4 个答案:

答案 0 :(得分:1)

我认为你走在正确的轨道上。使用name=record[]。你会得到像

这样的东西
$_POST['record'] = array(
    "record" =>  array(
        "value",
        "value",
        "value"
    ),
    "field2" =>  array(
        "value",
        "value",
        "value"
    ),
    "field3" =>  array(
        "value",
        "value",
        "value"
     )
);

所以要获得每一行,你要使用

$cnt = count( $theArray['record'] );
for ($x=0; $x<$cnt; $x++){
    echo $theArray['record'][$x];
    echo $theArray['field2'][$x];
    echo $theArray['field3'][$x];
}

答案 1 :(得分:1)

您无法轻易获得所需内容,但可以使用name="record[input1][]"(以及input2等),结果为:

$_POST['record'] = array(
    "input1"=>array(
        "value", "value", "value"
    ),
    "input2"=>array(
        "value", "value", "value"
    ),
    "input3"=>array(
        "value", "value", "value"
    )
);

然后您可以将其转换为所需的格式,如下所示:

$out = Array();
foreach(array_keys($_POST['record']['input1']) as $i) {
    foreach($_POST['record'] as $k=>$v) {
        $out[$i][$k] = $v[$i];
    }
}

答案 2 :(得分:0)

我刚试过 -

<form action="" method="post">
<input type="text" name="record['set1'][]" />
<input type="text" name="record['set1'][]" />
<input type="text" name="record['set1'][]" />
<input type="text" name="record['set2'][]" />
<input type="text" name="record['set2'][]" />
<input type="text" name="record['set2'][]" />
<input type="text" name="record['set3'][]" />
<input type="text" name="record['set3'][]" />
<input type="text" name="record['set3'][]" />
<input type="submit" value="submit" />
</form>

输出 -

Array
(
    [record] => Array
        (
            ['set1'] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                )

            ['set2'] => Array
                (
                    [0] => 4
                    [1] => 5
                    [2] => 6
                )

            ['set3'] => Array
                (
                    [0] => 7
                    [1] => 8
                    [2] => 9
                )

        )

)

这是你想要的吗?

答案 3 :(得分:0)

我认为这对你来说会更清楚,

$record = array();
foreach($_POST['record'] as $val){
   $record[] = $val;
}
print_r($record);