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”字段。联系人字段允许他们在个人资料中添加一个新的联系人。而且,他们可以按自己想要的次数点击这个按钮,它会创建许多“联系人”字段。
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:
但问题是,我很难计算添加了多少“联系人”文件。以下是单击按钮时生成的一些HTML:
<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>
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.
每次单击按钮时,name=“member[0][lname]”将变为name=“member[1][lname]”,并在每次单击按钮时继续增加。如前所述,用户可以在页面上任意多次执行此操作。
I am using PHP to loop through the multidimensional array:
我正在使用PHP对多维数组进行循环:
$array = $_POST['member'] ;
foreach($array as $array_element) {
$fname = $array_element['fname'];
$lname = $array_element['lname'];
}
How can I use PHP to determine how many fileds have been added so I can loop through them?
如何使用PHP确定添加了多少文件,以便循环使用?
Any help is greatly appreciated!
非常感谢您的帮助!
1 个解决方案
#1
6
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'];
}
}
#1
6
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'];
}
}