我正在为人们设置新的表单服务,该表单最多应包含4个同名输入。该表单有2个双输入,一个用于Money,另一个用于服务名称。
<input name='budget[]' id='' placeholder='Product or Service' type='text' class='form-control'>
<input name='budget_price[]' id='currency' placeholder='Value' type='number' class='form-control'>
<input name='budget[]' id='' placeholder='Product or Service' type='text' class='form-control'>
<input name='budget_price[]' id='currency' placeholder='Value' type='number' class='form-control'>
如何做一个foreach事后将其插入数据库?
答案 0 :(得分:1)
如评论中所述,您需要循环一个数组并使用key来访问另一个数组。
尝试一下:
<?php
$budget = $_POST['budget'];
$budgetPrice = $_POST['budget_price'];
foreach ($budget as $key => $entry) {
$serviceName = $entry;
$currency = $budgetPrice[$key];
// insert $serviceName and $currency into DB
// first iteration of loop is the first two inputs
}
或者,如果您想采用另一种方法(或无法选择要循环播放的数组),则可以使用for
循环:
<?php
$budget = $_POST['budget'];
$budgetPrice = $_POST['budget_price'];
$totalBudget = count($budget);
for ($i = 0; $i < $totalBudget; $i++) {
$serviceName = $budget[$i];
$currency = $budgetPrice[$i];
// insert $serviceName and $currency into DB
// first iteration of loop is the first two inputs
}
我假设用于每个数组中元素数量之间没有间隙的逻辑(例如count($budget) == count($budgetPrice)
返回true
)是预先处理的。
根据您的最后评论,您需要在插入变量之前检查变量是否为空,例如:
<?php
if (!empty($serviceName)) {
// insert $serviceName
}
if (!empty($currency)) {
// insert $currency
}