【问题标题】:How To Exclude Unselected Items (PHP)如何排除未选择的项目 (PHP)
【发布时间】:2012-08-23 20:14:30
【问题描述】:

我目前正在处理此订单: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>';
}
?>

【问题讨论】:

    标签: php


    【解决方案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)
    

    【讨论】:

    • @andrewsi,如果用户输入“0”,这将不起作用。您还应该检查if (empty($item['how_many']) || $item['how_many']=="0" )
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2015-06-09
    • 2011-04-25
    相关资源
    最近更新 更多