Reputation: 6986
I have a some values in my $_POST that are in there own arrays similar to this,
array(
['conviction_date'] = array(
[0] => 12/01/2011
[1] => 22/12/2011
)
['conviction_description'] = array(
[0] => This some text to show what the conviction was for etc.
[1] => This is some more text to show what the second convication was for
)
)
What I want to know is how do I loop through said arrays so that I can value from one to the match the value of the other via there keys?
Is it as simple as this,
foreach ($_POST['conviction_date'] as $k => $v) {
$newArray[] = array(
'conviction_date' => $v,
'conviction_details' => $_POST['conviction_details'][$k]
)
}
Will this then output something to the following?
array(
[0] => array(
'conviction_date' => 12/01/2011
'conviction_details' => This is some to show what the conviction was for etc.
),
[1] => array()
'conviction_date' => 22/11/2011
'conviction_details' => This is some more text to show what the second convication was for
)
Is there away to build a simpler array?
Upvotes: 0
Views: 561
Reputation: 17166
Your code sample has a few errors, e.g. conviction date: 12/01/2011 should probably be '12/01/2011'.
That aside, your proposed solution seems appropriate. Alternatively, if each date for a set of convictions is unique(!) you could also use the date as key (e.g. as UNIX-timestamp, or in YYYYMMDD-format). Retrieving the data would then be as simple as:
foreach ($convictions as $date => $description) { ... }
Upvotes: 0
Reputation: 96159
Might be simpler to give the parameters names so that php will create an array like
array( 'conviction'=>array(
0=>array('date'=..., 'details'=>...),
1=>array('date'=..., 'details'=>...),
...
);
Then you can do something like
foreach( $_POST['conviction'] as $c ) {
echo $c['date'], ' ', $c['details'], "\n";
}
A simple demo form:
<form method="post" action="...">
<fieldset><legend>0</legend>
<input type="text" name="conviction[0][date]">
<input type="text" name="conviction[0][details]">
</fieldset>
<fieldset><legend>1</legend>
<input type="text" name="conviction[1][date]">
<input type="text" name="conviction[1][details]">
</fieldset>
...
</form>
Upvotes: 0
Reputation: 2947
Edit the form to the following might be simpler:
<form method="post" action="">
<input type="text" name="conviction_date[]">
<input type="text" name="conviction_details[]">
</form>
if (isset($_POST) { var_dump($_POST); }
Upvotes: 1