问题:
您有一个表单,它生成多个输入字段,其中数组为他们的姓名(例如姓名[]和电子邮件[])。当您在 PHP 中检索这些输入时,您最终会得到一个连接的字符串而不是单个数组。如何将这些输入转换为正确的数组?
解决方案:
将表单输入数组转换为 PHP 中的单独数组:
实现:
$name = $_POST['name']; $email = $_POST['account']; foreach ($name as $key => $n) { // Get the corresponding email address using the key $e = $email[$key]; // Print the values or process them as needed echo "The name is $n and email is $e, thank you\n"; }
示例:
考虑以下形式:
<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[]" />
当您提交此表格时, $_POST 数组将包含以下内容:
$_POST = [ 'name' => ['name1', 'name2', 'name3'], 'email' => ['email1', 'email2', 'email3'], ];
使用上述解决方案,您可以轻松访问和处理表单输入:
foreach ($_POST['name'] as $key => $n) { $e = $_POST['email'][$key]; echo "The name is $n and email is $e, thank you\n"; }
输出:
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
以上是如何在 PHP 中正确访问和处理表单输入数组?的详细内容。更多信息请关注PHP中文网其他相关文章!