How can I loop through an array of dates and group by week, month or custom quarter?

别说谁变了你拦得住时间么 提交于 2020-01-03 05:31:04

问题


I am pulling out rows from a database based on date range and order by date, for example

SELECT date, code FROM records WHERE personid = '133'AND date >= '2017-02-10' AND date <= '2017-06-13' AND code IN ('P','T') ORDER BY date ASC 

These records I like to group or order in particular ways.

One way has grouped the records by consecutive dates, for this, I have the following function:

 function getRecordsWithIntervals(array $records, $interval_size)
            {
                $intervals = array();
                foreach (array_chunk($records, $interval_size) as $interval_records) {
                    $first_record = reset($interval_records);
                    $interval = array(
                        'start' => $first_record['date'],
                        'codes' => array_column($interval_records, 'code'),
                        'count' => count($interval_records),

                    );
                    $intervals[] = $interval;
                }
                return $intervals;
            }

For a consecutive 5 days I call the function, like

getRecordsWithIntervals($records, 5);

But now I like to add the feature of the weekly, monthly or custom quarter. So for example:

getRecordsWithIntervals($records, 'weekly');

Would order/grouped $records per Mo-Sunday interval within the date range 2 Feb 2017 - 13 jun 2017???

This would be some sample data

I like to plot this Google chart

And this would be the generated JS with PHP for Feb and March

['Feb 6-12, 2017’,1,’1’],
['Feb 13-19, 2017’,4,’4’],
['Feb 20-26, 2017’,4,’4’],
['Feb 27-??, 2017’,5,’5’],
['Mar 6-12, 2017',5,'5'],
['Mar 13-19, 2017',5,'5'],
['Mar 20-26, 2017’,3,’3’],
['Mar 27-xx, 2017’,4,’4’],

回答1:


MySQL might be a better place to conceptually form groups with your data. For example, if you wanted to have the week number and month on tap you could just add these items to your select clause:

SELECT
    date,
    WEEK(date) AS week,
    MONTH(date) AS month,
    code
FROM records
WHERE
    personid = '133' AND
    date BETWEEN '2017-02-10' AND '2017-06-13' AND
    code IN ('P','T')
ORDER BY date;


来源:https://stackoverflow.com/questions/48658979/how-can-i-loop-through-an-array-of-dates-and-group-by-week-month-or-custom-quar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!