我是PHP的新手。这是我的mailing.php中的代码。当用户提交请求时,有5-7个可选字段和20-25个字段最终未被选中。输出列出所有字段和值,无论它们是空还是已被选中。我知道我需要使用unset
或array_filter
,但无法弄清楚我需要在代码中插入的方式和位置。
if($_POST && count($_POST)) {
$body = '';
foreach($_POST as $key=>$value)
$body .= $key . ": " . $value . "\r\n";
mail("email@email.com", "Email Received at email@email.com", $body);
答案 0 :(得分:2)
你可以试试这个
if($_POST && count($_POST)) {
$_POST = array_filter($_POST);
$body = '';
foreach($_POST as $key=>$value)
$body .= $key . ": " . $value . "\r\n";
mail("email@email.com", "Email Received at email@email.com", $body);
OR
if($_POST && count($_POST)) {
$body = '';
foreach($_POST as $key=>$value){
$trim_value = trim($value);
if (!empty($trim_value)){
$body .= $key . ": " . $value . "\r\n";
}
}
mail("email@email.com", "Email Received at email@email.com", $body);
答案 1 :(得分:0)
在foreach循环之前,你应该使用这个
$_POST = array_filter($_POST);
另一个选择是使用条件内部foreach循环
foreach($_POST as $key=>$value)
if ($value != '' && $value != null)
$body .= $key . ": " . $value . "\r\n";