如何将表单输入数组转换为 PHP 数组 [英] How to get a form input array into a PHP array

查看:17
本文介绍了如何将表单输入数组转换为 PHP 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于下面的表单,它发布到 contacts.php,用户可以使用 jQuery.

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[]" />

如果我用下面的代码在 PHP 中将它们回显,

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;
}

我会得到这样的东西:

name1name2name3email1email2email3

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:

名字是name1,邮箱是email1,谢谢名字是name2,邮箱是email2,谢谢名字是name3,邮箱是email3,谢谢

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

推荐答案

它们已经在数组中了:$name 是一个数组,$email 也是如此

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\n";
}

要处理更多输入,只需扩展模式:

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\n";
}

这篇关于如何将表单输入数组转换为 PHP 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆