如何定义一个表单域数组PHP [英] How to define an array of form fields PHP

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

问题描述

我有一个问题.

我在第一页中有以下代码:

I have this code in the first page:

<input type="text" name="number" id="number">
<input type="submit" name="button_add" id="button_add" value="add">
<? 
$i=0;
while($number>$i) { $i++; ?>
  <div align="left">
  <input type="text" name="text[<? echo $i; ?>]" id="text[<? echo $i; ?>]" /><? } 
?>

如何使用$_POST vars在下一页中定义文件数组?

How do I define the array of fileds in the next page using $_POST vars?

推荐答案

$_POST中的条目本身就是一个数组,如果那是您要的内容:

The entry in $_POST is itself an array, if that's what you're asking:

for ($i = 0; $i < count($_POST['text']); ++$i) {
    // do something with this post:
    $_POST['text'][$i];
}

或:

foreach ($_POST['text'] as $i => $text) {
    // do something with:
    $text;
    // Note: $text === $_POST['text'][$i]
}

离题

始终关闭元素:

Off-topic

Always close your elements:

<input type="text" name="number" id="number" />
<input type="submit" name="button_add" id="button_add" value="add" />

您还忽略了关闭包裹text[]输入的<div>.否则,您的文档格式不正确,尽管浏览器会尝试解析该文档,但不能保证它们会按照您想要的方式进行操作.

You also neglected to close the <div> wrapping the text[] inputs. If you don't, your document is ill-formed and, though browsers will attempt to parse the document, there's no guarantee they'll do it the way you want.

输入的默认类型是文本.将type属性设置为"text"并没有什么害处,但这不是必需的.

The default type for inputs is text. It doesn't hurt to set the type attribute to "text", but it isn't necessary.

不要依赖短标签;使用完整的<?php.并非所有主机都会启用它们,它们已被弃用,并且很快就会消失(有一些关于在PHP 5之前废弃它们的讨论).

Don't rely on short tags; use the full <?php. Not all hosts will have them enabled, and they're deprecated and will be going away soon (there's been some talk about doing away with them before PHP 5).

您不需要为输入名称显式分配数组索引; 空括号会导致要分配给数组末尾的值.此外,"["和]"不是 ID的有效字符.

You don't need to explicitly assign array indices for your input names; empty brackets will cause the value to be assigned to the end of the array. Also, '[' and ']' aren't valid characters for IDs.

<input type="text" name="text[]" id="text_<?php echo $i; ?>" />

一个 for循环更多而不是代码中的while循环.尽管两者都做同样的事情,但是它们具有不同的含义(在不断变化的环境中,while循环重复而某些静态条件保持不变; for循环在序列上重复).

A for loop is more appropriate than a while loop in your code. Though both do the same thing, they have different connotations (a while loop repeats while some static condition holds under changing circumstances; a for loop repeats over a sequence).

for ($i=0; $i < $number; ++$i) {

我们在一起:

<input name="number" id="number" />
<input type="submit" name="button_add" id="button_add" value="add" />
<?php for ($i=0; $i < $number; ++$i): ?>
  <div align="left">
    <input name="text[]" id="text_<?php echo $i; ?>" />
  </div>
<?php endfor; ?>

这篇关于如何定义一个表单域数组PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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