0

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

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

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

我想要的是将其以如下格式发送到 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[]" />

但这只是 1 个输入元素。有没有办法得到一个像上面那样有 3 个元素的结构?

谢谢你。

4

4 回答 4

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];
}
于 2012-06-22T15:36:13.370 回答
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];
    }
}
于 2012-06-22T15:36:34.097 回答
0

我想这对你来说会更清楚,

$record = array();
foreach($_POST['record'] as $val){
   $record[] = $val;
}
print_r($record);
于 2012-06-22T15:43:08.517 回答
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
                )

        )

)

这是你想要的吗?

于 2012-06-22T15:40:58.203 回答