Reputation: 39
I am trying to get the data from the form I created where I used an array to name them like:
<input type="text" name="fname[]" />
<input type="text" name="mname[]" />
<input type="text" name="lname[]" />
where the said form field are dynamically inserted or removed in the page.
On my script to get the values of the forms, I wrote something like:
$student = array(
'fname' => '$_POST[fname]',
'mname' => '$_POST[mname]',
'lname' => '$_POST[lname]',
);
But when I used var_dump to see the values, each field will be indexed from zero and if it has repeating fields, it would be again be declared as another array inside an array.
What I wanted to do is to have an array with this stucture:
$student = array(
array(
'fname' => 'fname1',
'mname' => 'mname1',
'lname' => 'lname1'
),
array(
'fname' => 'fname2',
'mname' => 'mname3',
'lname' => 'lname2'
)
);
I tried using a loop but I just fail again and again. Can anyone help me solve this problem?
Thank you in advance for your help.
Upvotes: 0
Views: 94
Reputation: 22783
Oops, I thought Stephan's answer would suffice, but rather, it should be the following I believe (can't test right now). Try it:
<input type="text" name="student[0]['fname']" />
<input type="text" name="student[0]['mname']" />
<input type="text" name="student[0]['lname']" />
<input type="text" name="student[1]['fname']" />
<input type="text" name="student[1]['mname']" />
<input type="text" name="student[1]['lname']" />
etc...
(note the added numeric indexes)
Then when you do a echo '<pre>' . print_r( $_POST[ 'student' ], true );
you should see the structure you are looking for.
Upvotes: 0
Reputation: 189
<input type="text" name="student[]['fname']" />
<input type="text" name="student[]['mname']" />
<input type="text" name="student[]['lname']" />
no loops necessary. Your $_POST['student']
variable will automatically be the array you wanted to achieve.
EDIT: this isn't achieving the desired result. It's incrementing student
for each field. adding an n
value to the first set of brackets like student[n][fname]
does achieve the desired result. I don't know how the script is written to dynamically generate these three fields on the fly, but if you can figure out how to add an n
value you're golden.
Upvotes: 2
Reputation: 688
<?php
for($i=0; $i<count($_POST['fname']); $i++) {
$student[] = array(
'fname' => $_POST['fname'][$i],
'mname' => $_POST['mname'][$i],
'lname' => $_POST['lname'][$i],
);
}
?>
Upvotes: 0