简体   繁体   English

PHP日期范围(不使用MySql日历表)

[英]PHP Date range (not using MySql calendar table)

I have a data range that I need to pull results from a database. 我有一个数据范围,需要从数据库中提取结果。 Usual problem, not every day has records, and its skewing my charts. 通常的问题是,并非每天都有记录,并且它歪曲了我的图表。 I need to pad the results with 0s and have a question on the best way. 我需要用0填充结果,并且对最佳方法有疑问。

I have a php routine that populates an array with the correct number of days, and need to cycle through my mysql.recordset inserting the values if there is one into the array for that day in the loop, or leaving it as zero if not. 我有一个php例程,用正确的天数填充数组,并且需要循环遍历我的mysql.recordset,如果该天在循环中的数组中有一个值,则将其插入值;否则,将其保留为零。

What is the best way to carry out the search/comparison without having to loop through the whole recordset to see if there is any data for the date I am processing in the loop. 进行搜索/比较的最佳方法是什么,而不必循环遍历整个记录集以查看循环中是否有我正在处理的日期的数据。

Assuming theres 90 days, thats a loop through 90 records for each day (90*90 , 8100 compares which scares me) 假设有90天,那就是每天遍历90条记录(90 * 90、8100比较这让我感到恐惧)

There will never be more than 366 records in a dataset. 数据集中的记录永远不会超过366条。

Using PHP latest versions. 使用PHP最新版本。

Create a 2D associative array, with the date being the first dimension. 创建一个二维关联数组,其中日期为第一维。 So you create an array $allrecords where the keys are '2012-01-01', etc., and the value of each of these is an associative array that mimics the other structure of your data, with zeroes throughout. 因此,您将创建一个数组$ allrecords,其键为'2012-01-01'等,并且每个键的值都是一个关联数组,该数组模仿您数据的其他结构,且始终为零。 So if your data looks like: 因此,如果您的数据如下所示:

DATE        FIELDA   FIELDB   FIELDC
2012-01-01      10       20       30
2012-01-03       1        2        3

You create the array so that 您创建数组,以便

$allrecords["2012-01-01"]["FIELDA"]=0;
$allrecords["2012-01-01"]["FIELDB"]=0;
$allrecords["2012-01-01"]["FIELDC"]=0;
$allrecords["2012-01-02"]["FIELDA"]=0;
etc.

You would loop through your dataset only once, doing somthing like 您只会遍历数据集一次,做类似的事情

$allrecords["2012-01-01"]["FIELDA"]=10;
$allrecords["2010-01-01"]["FIELDB"]=20;
$allrecords["2010-01-01"]["FIELDC"]=30;
get next record
$allrecords["2010-01-03"]["FIELDA"]=1;
etc.

Then you loop through the array to do your output. 然后,您遍历数组以执行输出。

Or if you can change the query, you could create a temporary table of the dates you want and join it to the results and bring the data in with the gaps filled. 或者,如果您可以更改查询,则可以创建所需日期的临时表,然后将其加入结果中,并填充空白。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM