使用 PHP 在 MySQL 数组中搜索日历日期?
我正在构建一个日历,当涉及到数组时我真的很愚蠢。 首先,我需要查询我的数据库,所以:
$events = mysql_query ("SELECT id,title,date WHERE date BETWEEN 2009-01-01 AND 2009-01-31")
or die(mysql_error());
所以,现在我需要对这些事件进行排序,这样,当我回显我的日历表时,我可以检查这个数组中的事件。 在这个伟大的 由 David Walsh 编写的日历中,他每天都会进行查询,但我想它会成为一场性能噩梦。 那么...有什么想法我该怎么做吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,确保您将日期与日期进行比较。我认为您的代码应该是(即在
date
周围用单引号):假设
date
是日期列。First up, make sure you're comparing dates with dates. I think your code should be (i.e. with single quotes around
date
):assuming
date
is a date column.我会在一个优雅的 for 循环中做到这一点
现在你有一个数组,用它做一些事情
将返回该数组中事件的每个 id
i would do that in a elegant for loop
now you have an array do somethingg with it like this
will return each id for events in that array
好的,关于您的评论,您可以执行以下操作:获取像 Davek 提议的事件(注意
ORDER BY
!)然后您就得到了按日期排序的事件。要输出它,您可以执行以下操作:
注意:这只是一个粗略的草图,您当然必须调整输出,但它应该给您正确的想法。
输出将如下所示(在我的示例中):
注释后编辑:
您可以编写自己的函数:
但是这样您每天都会一遍又一遍地搜索完整的数组。如果您从
$events
数组中删除已搜索的事件,则可以改进它。所以每次你在一个较小的数组中搜索。但只有在出现性能问题时我才会这样做。Ok regarding your comments you can do something like this: Get the events like Davek proposed (note the
ORDER BY
!)Then you got the events ordered by the date. To output it you can do this:
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):
Edit after comment:
You can write your own function:
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.