这是我的代码。
<?php
if(isset($_POST['submit']) {
$currency = $_POST['currency'];
$amount = $_POST['amount'];
$integer = 0;
//Loop using while, check the count
while(count($currency) > $integer) {
$currencyArray = array(
'currency' => $currency[$integer],
'amount' => $amount[$integer]
);
//Insert statement constructed to array
//..... insert into
//Stop loop when reach to the limit
$integer = $integer + 1;
}
}
?>
<form action = "" method = "post">
<input type="checkbox" class="currency" name="currency[]" value="USD">USD
<input type="text" name="amount[]" value = "">
<input type="checkbox" class="currency" name="currency[]" value="EUR">EUR
<input type="text" name="amount[]" value = "">
<input type="checkbox" class="currency" name="currency[]" value="JPY">JPY
<input type="text" name="amount[]" value = "">
<input type="checkbox" class="currency" name="currency[]" value="PHP">PHP
<input type="text" name="amount[]" value = "">
<input type = "submit" name = "submit">
</form>
注:括号()为金额
我有一种情况,如果我按顺序输入货币,比如我选择美元并输入金额(50),然后是欧元(2,在字段中正确保存金额,但如果我选择欧元(50)和日元(500。第一条记录必须是50,第二条记录必须为500。我缺了什么吗?
编辑:
<?php
if(isset($_POST['submit']) {
$currency = $_POST['currency'];
$amount = array();
$integer = 0;
foreach($_POST['amount'] as $amount_value) {
if($amount_value != '') {
$amount[] = $amount_value;
}
}
//Loop using while, check the count
while(count($currency) > $integer) {
$currencyArray = array(
'currency' => $currency[$integer],
'amount' => $amount[$integer]
);
//Insert statement constructed to array
//..... insert into
//Stop loop when reach to the limit
$integer = $integer + 1;
}
}
?>
编辑阵列结果
金额:阵列([0]=>[1]=>25[2]=>[3]=>50[4]=>[5]=>25[6]=>50)
对于货币:数组([0]=>欧元[1]=>日元)
这就是为什么,因为amount[]总是被设置的,因为没有值也是文本字段中的值!只有选中复选框时,才会设置另一侧的货币。
因此count($amount)
总是4,而count($currency)
取决于所选的复选框。
如果您现在选择50欧元和100日元并在数组中循环,则会发生以下情况:
$amount[0] = ""
,因为第一个金额字段为空
$currency[0] = "EUR"
,因为美元被忽略
$amount[1] = "50"
,因为50在下一个字段,即EUR
$currency[1] = "JPY"
,因为下一个复选框是JPY
根据您的代码,如果您打印出$amount
,您将看到以下内容:
$amount[0] equals ""
$amount[1] equals "50"
$amount[2] equals "500"
$amount[3] equals ""
当你的$currency[0]
等于"EUR",$currency[1]
等于"JPY"时,这与你的想法不一致。
在执行while循环之前,您需要手动从$amount
中删除这些空值
编辑:使用解决方案更新,使用array_filter()
删除$amount数组中的空值
$amount = array_filter($amount);
array_filter():"如果没有提供回调,则所有等于FALSE的输入项都将被删除。"