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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大