如何排除未选择的项目(PHP)

时间:2012-08-23 20:14:31

标签: php

我目前正在处理此订单:http://www.libertydelimart.com/order

现在,所有项目都会发布到我的电子邮箱中 - 无论天气信息是否输入“多少”文本框。

排除“如何输入”中没有输入任何内容的项目的最佳方式是什么? 许多“文本框,以便只有输入信息的项目通过电子邮件发送给我?

<?php
if(isset($_POST['submit'])) {

$to = "test@mywebsite.com"; 
$subject = "New Order";
$name_field = $_POST['name'];
$phone_field = $_POST['phone'];
$food = $_POST['food'];

$body = 'Name: ' . $name_field . PHP_EOL . 'Phone: ' . $phone_field . PHP_EOL;

//Check if any food items were set in order to prevent foreach error
if($food){
  foreach ($food as $key => $item) {
    $body .= $key . ' - ' . $item ['how_many'];
    if($item['customize']) $body .= ' ('.$item['customize'].')' . PHP_EOL;
  }  
}

echo "Your Order Will Be Ready In 30 Minutes!";
mail($to, $subject, $body,"FROM: Deli <$to>");
print '<pre>'.$body.'</pre>';
}
?>

1 个答案:

答案 0 :(得分:1)

使用foreach中的empty()检查其是否为空:

foreach ($food as $key => $item) {
    if (!empty($item['how_many'])) {
        // Add to body only if it isn't empty
        $body .= $key . ' - ' . $item ['how_many'];
        if($item['customize']) $body .= ' ('.$item['customize'].')' . PHP_EOL;
    }
} 

请记住,这不会验证输入实际上是否为数字。或者,我建议实施this SO answer,并检查它是否大于零。

if ((string)(int)$item['how_many'] == $item['how_many'] && (int)$item['how_many'] > 0)