【问题标题】:Proper way to query inside a for loop在 for 循环中查询的正确方法
【发布时间】:2014-02-28 04:55:23
【问题描述】:

因为我在谈论 wp_Queries,所以我对于是否将其发布在 WP Answers 或此处存在冲突,但我认为这更像是一个一般性的 PHP 问题,所以就这样吧。

我正在一个项目中构建一个事件日历功能。如果您需要视觉效果,可以在这里看到我到目前为止所拥有的:http://theseattlevine.com/wordpress2014/calendar/?m=Feb&y=2014

使用与 date() 和 strtotime() 函数通信的查询参数生成天数(由正方形表示,如普通日历)适当的日子(周一至周日)。我正在使用 for 循环根据每个月的天数生成有限次数的正方形。

现在,显然我想在每个方格内列出当天发生的事件。在我的大脑中,最合乎逻辑的方法是在每个方格中设置一个查询循环,查找日期在当天上午 12:00 到晚上 11:59 之间的所有事件,然后回显每个事件的标题。但是,这种类型的查询似乎不能在 for 循环中工作,我所做的研究让我相信将循环放在 for 循环中是一个坏主意,因为它会创建大量或请求服务器。

最后,我的问题是,最好的方法是什么?如何在每次出现 for 循环时从数据库(如 Wordpress 中的 wp_query)中查询帖子?

【问题讨论】:

    标签: php wordpress for-loop


    【解决方案1】:

    我会尝试以不同的方式来做。在一个页面上抛出 30xn 请求,并让 m 个用户查看该页面,您的数据库最终会哭泣。

    这个怎么样?

    1. 从 SQL 中获取当月的所有事件,将它们放入这样的数组中:$event[$dayofmonth][title]=$title

    2. $date[$weeknumber][$dayofweek]=$dayofmonth 之类的形式获取另一个数组,以帮助构建日历框架

    3. 然后,当您遍历 $date 以构建日历框架时,您可以使用 $dayofmonth 来引入事件标题,或者如果您将其构建到事件数组中,则可以提供更多详细信息。

    这样你只需要 1 个查询(很有可能你可以只使用 php 来构建 $date 数组。

    示例代码如下:

    /********** Build $event **********/
    $result=however_you_get_your_mysql_result(); //You bound to know the SQL part.. the result set should already be filtered to just this month only
    $event=array();
    foreach($result as $r){  // In here I assume you have at least a title and a event_start_time in resultset
       $dayofmonth=date("Y-m-d",strtotime($r['even_start_time'])); // To get just the date part
       $event[$dayofmonth]['title']=$r['title'];
       $event[$dayofmonth]['detail']=$r['detail']; // If you have detail or other fields.
    }
    
    /********** Build $date **********/
    $when=date('Y-m-d'); // Let's say this month
    $year=date('Y', strtotime($when));
    $first_week_of_month=date('W', strtotime(date('Y-m',strtotime($when))));  //wk number of first day in month
    $last_week_of_month=date('W',strtotime(date('Y-m-t', strtotime($when)))); // wk number of last day in month
    $date=array();
    for($w=$first_week_of_month; $w<$last_week_of_month+1; $w++){ // Set Week boundary 
       for($d=1; $d<8;$d++){  // For 7 weekdays
          $dayofmonth=date('Y-m-d',strtotime($year."W".$w.$d));
          $date[$w][$d]=$dayofmonth;
       }
    }
    

    【讨论】:

    • 啊哈!这很有意义。我只是需要有人来解开我的大脑关于最基本的步骤,谢谢!
    • 原来我仍然有这个问题。您能否发布您将使用什么代码来创建您提到的数组?
    【解决方案2】:

    如果您创建另一个以以下格式存储数据的表: 日期 ||事件名称

    那么从这个表中查询具体的日期就很容易了。

    【讨论】:

      猜你喜欢
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2023-03-31
      • 2015-08-12
      • 2020-12-04
      • 2020-07-14
      相关资源
      最近更新 更多