Reputation: 71
I have a table for employee time-sheet.
After filling this time-sheet form I get below array.
Array
(
[date_from] => 2018-01-04
[date_to] => 2018-01-04
[date] => 2018-01-04
[project] => 53
[task] => 1
[time] => 05:30
[date1] => 2018-01-05
[project1] => 54
[task1] => 1
[time1] => 08:00
)
Now I want this array as
Array
(
[date] => Array
(
[date_from] => 2018-01-04
[date_to] => 2018-01-04
)
[row1] => Array
(
[date] => 2018-01-04
[project] => 53
[task] => 1
[time] => 05:30
)
[row2] => Array
(
[date1] => 2018-01-04
[project1] => 53
[task1] => 1
[time1] => 05:30
)
)
some one please help me to this thing sort out.
Upvotes: 0
Views: 302
Reputation: 22911
PHP already formats array nicely with arrays by including []
in your form. You should modify your incoming form like so (This is one example via jQuery, but there are many other ways to add additional rows with an index):
var i = 0;
function addRow() {
i++;
$('#form')
.append($('<br />'))
.append('Date: ')
.append($('<input />').attr('name', 'form[' + i + '][date]'))
.append('Time: ')
.append($('<input />').attr('name', 'form[' + i + '][time]'))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="form">
Date: <input name="form[0][date]" />
Time: <input name="form[0][time]" />
</div>
<input type="button" value="Add new" onclick="addRow()" />
The reason why I index the rows, is so that $_POST['form'][0]
will contain both a date/time, and is segmented.
foreach ( $_POST['form'] as $dateTimeVals ) {
//$date = $dateTimeVals['date'];
//$time = $dateTimeVals['time'];
//Sweet
}
I could simply omit the index, and use date[]
and time[]
but then will have to do a for loop to get the data:
for ($i=0; $i<count($_POST['date']); $i++) {
//$date = $_POST['date'][$i];
//$time = $_POST['time'][$i];
}
Upvotes: 3
Reputation: 12332
Please please please try to use @FrankerZ solution, otherwise you may have to resort to manually testing the field name against a "white list" to determine what makes up a row
$postData = Array(
'date_from' => '2018-01-04',
'date_to' => '2018-01-04',
'date' => '2018-01-04',
'project' => '53',
'task' => '1',
'time' => '05:30',
'date1' => '2018-01-05',
'project1' => '54',
'task1' => '1',
'time1' => '08:00'
);
$rows = array();
$rowKeys = array( 'date','project','task','time');
foreach( $postData as $key => $value )
{
if( preg_match('/\A(\D*)(\d*)\z/', $key, $match ) === 1 and in_array( $match[1], $rowKeys ) === true )
{
$rowKey = ( isset( $match[2] ) and empty( $match[2] ) === false ) ? 'row' . ($match[2] + 1) : 'row1';
if( isset( $rows[ $rowKey ] ) === false )
{
$rows[ $rowKey ] = array();
}
$rows[ $rowKey ][ $match[1] ] = $value;
unset( $postData[ $key ] );
}
}
$rows = array_merge( array( 'date'=> $postData ), $rows );
print_r( $rows );
Upvotes: 0