Reputation: 6367
I have Input fields that result in an array after 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>
This will be return:
Array (
['day'] => Array ( [0] => 1 [1] => 2 ) ['from] => Array ( [0] => 1 [1] => 2 ) ['to] => Array ( [0] => 1 [1] => 2 )
)
But I would like to have this:
Array ( [1] => Array
( ['day'] => 1 ['from] => 1 ['to] => 1 ) [2] => Array ( ['day'] => 2 ['from] => 2 ['to] => 2 )
)
I get this if I use:
<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>
But here comes the problem. I want to add new rows dynamicly (with JS) and would need to add always +1 to the first index.
How could I achive the second result without having to set the first index manually?
Upvotes: 0
Views: 2934
Reputation: 213
Using script to write script is better than to write each. Just a concept to go with, you can use jquery to write into div for better result.
<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 )">
Upvotes: 0
Reputation: 12508
You can keep your html like this -
<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>
After you get the values on server, lets say in GET array -
<?php
$myfinalarray = array();
foreach ($_GET['time'] as $key => $value) {
foreach ($value as $k => $v) {
$myfinalarray[$k][$key] = $v;
}
}
print_r($myfinalarray);
?>
Output -
Array
(
[0] => Array
(
['day'] => 1
['from'] => 1
['to'] => 1
)
[1] => Array
(
['day'] => 2
['from'] => 2
['to'] => 2
)
)
Upvotes: 2