如何用PHP计算动态HTML表单输入数组? [英] How to count a dynamic HTML form input array with PHP?

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

问题描述

我在页面上有一个按钮,当用户按下按钮时,它会在页面上创建另一个联系人"字段.联系人字段允许他们将新联系人添加到他们的个人资料.另外,他们可以根据需要多次单击按钮,它将创建那么多联系人"字段.

I have a button on a page that when a user pushes it, it creates another "Contact" field on the page. The Contact field allows them to add a new contact to their profile. Also, they can click the button as many times as they want, and it will create that many "Contact" fields.

问题是,我很难确定已经添加了多少个"Contact"文件.这是单击按钮时生成的一些HTML:

The problem though is that I am having a hard time figuring how many "Contact" fileds have been added. Here is some HTML that is generated when the button is clicked:

<div class="item">
    <label for="in-1v">First Name <span>*</span></label>
    <div class="text">
        <input type="text" id="in-1-0" name="member[0][fname]" value="" />
    </div>
</div>
<div class="item">
    <label for="in-2-0">Last Name <span>*</span></label>
    <div class="text">
        <input type="text" id="in-2-0" name="member[0][lname]" value="" />
    </div>
</div>

每次单击按钮时,name ="member [0] [lname]"将变为name ="member [ 1 ] [lname]",并且每次按钮持续增加被点击.如前所述,用户可以在页面上执行任意多次操作.

Each time the button is clicked, name="member[0][lname]" will become name="member[1][lname]" and will continue to increment each time the button is clicked. As stated earlier, the user can do this as many times as they want on the page.

我正在使用PHP遍历多维数组:

I am using PHP to loop through the multidimensional array:

$array = $_POST['member'] ;
foreach($array as $array_element) {
  $fname = $array_element['fname'];
  $lname = $array_element['lname'];
}

如何使用PHP确定已添加的文件数,以便我可以遍历它们?

How can I use PHP to determine how many fileds have been added so I can loop through them?

任何帮助将不胜感激!

推荐答案

您可以像这样简单地获得一个计数:

You can simply get a count like so:

$count = count($_POST['member']);

然后,您还可以修改循环,使其看起来像这样:

You could also then modify your loop to look like this:

// First check to see if member is set and is a valid array
if (!empty($_POST['member']) && is_array($_POST['member'])) {
    $count = count($_POST['member']);
    for ($i = 0; $i < $count; $i++) {
        $fname = $_POST['member'][$i]['fname'];
        $lname = $_POST['member'][$i]['lname'];
    }
}

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

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