我正在创建一个小程序来输入多个销售员的销售目标。仅当目标不为空时,如何获取推销员ID。
我正在使用隐藏的数组输入类型来存储销售员ID。但是每次我尝试获取目标字段不为空的推销员ID时,都会打印所有推销员ID。
这是输入:
<form method="POST" action="">
<input type="submit" name="send" value="send"><br/>
<?
$getSales = "SELECT sales_id, sales_name FROM SALESMAN";
$execSales = odbc_exec($conn,$getSales);
while(odbc_fetch_row($execSales)) {
$idSales = odbc_result($execSales,"sales_id");
$nameSales = odbc_result($execSales,"sales_name");
?>
<tr>
<input type="hidden" name="salesid[]" id="salesid">
<td><input type="text" name="target[]" id="target"></td>
</tr>
<?
}
?>
</form>
此表单将产生类似这样的结果
Sales Id || Target |
--------------------------
SLS0001 || |______30| | ==> 30 for sls0001
SLS0002 || |________| | ==> no target for sls0002
SLS0003 || |______10| | ==> 10 for sls0002
要获取目标不为空的salesid,请创建
foreach (array_filter($_POST['salesid']) as $key => $salesId)
{
echo $salesId.'<br/>';
}
我期望得到的结果是
SLS0001
SLS0003
但结果是
SLS0001
SLS0002
SLS0003
如何获得预期的结果?谢谢。
答案 0 :(得分:4)
如果我正确理解,我认为您需要检查$_POST['target']
是否为空,而不是salesid
。
您可以将array_combine与array_filter结合使用以实现此结果。在此处查看有关array_combine的更多信息:https://www.php.net/manual/en/function.array-combine.php
array_combine($_POST['salesid'], $_POST['target'])
将为您提供一个数组,如:
array(
'SLS0001' => '30',
'SLS0002' => '',
'SLS0003' => '10'
);
然后应用array_filter它将给您正确的结果。
// makes salesid your key, and target your value, array_filter will filter out empties from target
foreach (array_filter(array_combine($_POST['salesid'], $_POST['target'])) as $salesid => $target)
{
echo $salesid.'<br/>';
}
答案 1 :(得分:0)
foreach (array_filter($_POST['salesid']) as $key => $salesId)
{
if (!/* here you use condition for is empty or null */)
echo $salesId.'<br/>';
}