【问题标题】:PHP for each - else always returns else valuePHP for each - else 总是返回 else 值
【发布时间】:2017-02-01 13:08:33
【问题描述】:

我使用下面的代码发送报告,但是当我添加 else 语句时,即使 if 语句为真,也会返回所有内容。

谁能解释这是为什么?我认为我以前没有遇到过这个问题?

foreach ( $result as $page ) {
 $date1 = new DateTime($page->start_date);
 $date2 = new DateTime($page->end_date);

 if (strtotime($page->start_date) >= strtotime('today') && strtotime($page->start_date) < strtotime('tomorrow')) {

     $email_content .=  '<span style=" background-colour: #777777; font-size: 1em; font-family: arial, sans-serif; color:#202020;"><strong>' . $page->post_title . ' </strong></span>';

     $email_content .=  '<span style=" font-size: 1em; font-family: arial, sans-serif; color:#00b200;"><strong>Order By '  . $date1->format('d-m-y') . ' ' . '</strong></span>';

     $email_content .=  '<div style="  font-size: 1em; font-family: arial, sans-serif; color:#cc0000;"><strong>For Delivery '  . $date2->format('d-m-y') . '</strong></div><br>' . '<br>';

 }else {
     $email_content =  '<span style=" background-colour: #777777; font-size: 1em; font-family: arial, sans-serif; color:#202020;"><strong>tester </strong></span>';
 }
}    

感谢阅读:)

【问题讨论】:

  • 您使用 start_date 两次 - 您的意思是在第二次比较中使用 end_date 吗?
  • 代码未格式化 :) :) @jonny 你能把 else 条件的输出打印到以便我们得到准确的想法。
  • @trevor 是正确的 start_date 使用了两次,end_date 没有使用
  • 开始日期应该是那里的两倍,是基于开始的获取事件。问题是当我添加“else”时,即使有要返回的日期也会返回
  • 您确定条件为真吗?你能在你的foreach 中添加var_dump(strtotime($page-&gt;start_date)); var_dump(strtotime('today')); var_dump(strtotime('tomorrow')); echo '&lt;br /&gt;'; 并向我们展示输出吗?

标签: php wordpress loops if-statement


【解决方案1】:

当您遍历时,您的 $email_content 变量将在 else 语句中被覆盖。您在 if 中附加 .但覆盖在其他。尝试将您的代码更新为:

        foreach ( $result as $page ) {
     $date1 = new DateTime($page->start_date);
     $date2 = new DateTime($page->end_date);

     if (strtotime($page->start_date) >= strtotime('today') && strtotime($page->start_date) < strtotime('tomorrow')) {

         $email_content .=  '<span style=" background-colour: #777777; font-size: 1em; font-family: arial, sans-serif; color:#202020;"><strong>' . $page->post_title . ' </strong></span>';

         $email_content .=  '<span style=" font-size: 1em; font-family: arial, sans-serif; color:#00b200;"><strong>Order By '  . $date1->format('d-m-y') . ' ' . '</strong></span>';

         $email_content .=  '<div style="  font-size: 1em; font-family: arial, sans-serif; color:#cc0000;"><strong>For Delivery '  . $date2->format('d-m-y') . '</strong></div><br>' . '<br>';
    }else {
         $email_content .=  '<span style=" background-colour: #777777; font-size: 1em; font-family: arial, sans-serif; color:#202020;"><strong>tester </strong></span>';

 }
}  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-28
    • 2016-05-10
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    相关资源
    最近更新 更多