Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

How to get a form input array into a PHP array

I have a form like the one below which is posted to contacts.php, and the user can dynamically add more with jQuery.

<input type="text" name="name[]" />
<input type="text" name="email[]" />

<input type="text" name="name[]" />
<input type="text" name="email[]" />

<input type="text" name="name[]" />
<input type="text" name="email[]" />

If I echo them out in PHP with the code below,

$name = $_POST['name'];
$email = $_POST['account'];

foreach($name as $v) {
    print $v;
}

foreach($email as $v) {
    print $v;
}

I will get something like this:

name1name2name3email1email2email3

How can I get those arrays into something like the code below?

function show_Names($n, $m)
{
    return("The name is $n and email is $m, thank you");
}

$a = array("name1", "name2", "name3");
$b = array("email1", "email2", "email3");

$c = array_map("show_Names", $a, $b);
print_r($c);

so my output is like this:

The name is name1 and email is email1, thank you The name is name2 and email is email2, thank you The name is name3 and email is email3, thank you

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They are already in arrays: $name is an array, as is $email

So all you need to do is add a bit of processing to attack both arrays:

$name = $_POST['name'];
$email = $_POST['account'];

foreach( $name as $key => $n ) {
  print "The name is " . $n . " and email is " . $email[$key] . ", thank you
";
}

To handle more inputs, just extend the pattern:

$name = $_POST['name'];
$email = $_POST['account'];
$location = $_POST['location'];

foreach( $name as $key => $n ) {
  print "The name is " . $n . ", email is " . $email[$key] .
        ", and location is " . $location[$key] . ". Thank you
";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...