问题
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