duanbeng8872 2009-12-14 21:15
浏览 107
已采纳

在PHP中搜索MySQL数组中的日历日期?

I'm building a calendar and I'm really dumb when it comes to arrays. First of all, I need to query my database, so:


$events = mysql_query ("SELECT id,title,date WHERE date BETWEEN 2009-01-01 AND 2009-01-31")
or die(mysql_error());

So, now I need to order those events so, when I'm echoing my calendar table, I can check this array for events. In this great Calendar written by David Walsh, he does a query for every day, but I suppose it would be a performance nightmare. So...any ideas how can I do this?

  • 写回答

3条回答 默认 最新

  • doumao6048 2009-12-15 15:33
    关注

    Ok regarding your comments you can do something like this: Get the events like Davek proposed (note the ORDER BY!)

    $events = mysql_fetch_assoc(mysql_query ("SELECT id,title,date WHERE date BETWEEN '2009-01-01' AND '2009-01-31' ORDER BY date asc"));
    

    Then you got the events ordered by the date. To output it you can do this:

    $last_date = null;
    foreach($event in $events) {
        if($last_date !== $event['date']) {
            echo 'Events for day ' . $event['date'] . ": 
    ";
            $last_date = $event['date'];
        }
    
        echo $event['title'] . "
    "
    
    }
    

    Note: This is just a rough sketch, you have to adjust the output of course, but it should give you the right idea.

    Output would look like this (in my example):

    Events for 2009-01-01: 
    Event 1
    Event 2
    Events for 2009-01-02: 
    Event 1
    .
    .
    .
    

    Edit after comment:

    You can write your own function:

    function get_events($date, $events) {
        $result = array();
        foreach($event in $events) {
            if($event['date'] == $date) {
                $result[] = $event;
            }
        }
        return $result;
    }
    

    But this way you search the the complete array over and over again for each day. You can improve it, if you remove the events you already searched for from the $events array. So every time you search in a smaller array. But I would only do this if there is a performance issue.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch