在PHP中将输入字段保存为数组

时间:2014-09-19 20:01:00

标签: php html arrays html5

我有输入字段,在POST后产生一个数组:

<tr>
<td><input name="time['day'][]" value="1"></td>
<td><input name="time['from][]" value="1"></td>
<td><input name="time['to][]" value="1"></td>
</tr>

<tr>
<td><input name="time['day'][]" value="2"></td>
<td><input name="time['from][]" value="2"></td>
<td><input name="time['to][]" value="2"></td>
</tr>

这将是返回:

  

数组(

['day'] => Array
    (
        [0] => 1
        [1] => 2
    )

['from] => Array
    (
        [0] => 1
        [1] => 2
    )

['to] => Array
    (
        [0] => 1
        [1] => 2
    )
     

但我想有这个:

  

阵列(       [1] =&gt;阵列

    (
        ['day'] => 1
        ['from] => 1
        ['to] => 1
    )

[2] => Array
    (
        ['day'] => 2
        ['from] => 2
        ['to] => 2
    )
     

如果我使用的话,我会得到这个:

<tr>
<td><input name="time[1]['day']" value="1"></td>
<td><input name="time[1]['from]" value="1"></td>
<td><input name="time[1]['to]" value="1"></td>
</tr>

<tr>
<td><input name="time[2]['day']" value="2"></td>
<td><input name="time[2]['from]" value="2"></td>
<td><input name="time[2]['to]" value="2"></td>
</tr>

但问题出现了。我想动态地添加新行(使用JS),并且需要总是将+1添加到第一个索引。

如何在不必手动设置第一个索引的情况下实现第二个结果?

2 个答案:

答案 0 :(得分:1)

你可以像这样保持你的HTML -

<tr>
    <td><input name="time['day'][]" value="1"></td>
    <td><input name="time['from'][]" value="1"></td>
    <td><input name="time['to'][]" value="1"></td>
</tr>

<tr>
    <td><input name="time['day'][]" value="2"></td>
    <td><input name="time['from'][]" value="2"></td>
    <td><input name="time['to'][]" value="2"></td>
</tr>

在服务器上获取值后,让我们说在GET数组中 -

<?php 
    $myfinalarray = array();
    foreach ($_GET['time'] as $key => $value) {
        foreach ($value as $k => $v) {
            $myfinalarray[$k][$key] = $v;
        }
    }
    print_r($myfinalarray);
?>

输出 -

Array
(
    [0] => Array
        (
            ['day'] => 1
            ['from'] => 1
            ['to'] => 1
        )

    [1] => Array
        (
            ['day'] => 2
            ['from'] => 2
            ['to'] => 2
        )

)

答案 1 :(得分:0)

使用脚本编写脚本比编写脚本更好。只是一个概念,你可以使用jquery写入div以获得更好的结果。

<script>
function callInput( i ) {
  document.write( "<tr><td><input name='time[" + i + "][day]' value='" + i + "'></td><td><input name='time[" + i + "][from]' value='" + i + "'></td><td><input name='time[" + i + "][to]' value='" + i + "'></td></tr>" );
}

function callRow( i ) {
  document.write( "<table>" );
  for( a = 0; a < i; a++ ) {
    callInput( a );
  }
  document.write( "</table>" );
}
</script>

<body onload="callRow( 4 )">