$date = array('01-01-2019','02-01-2019','05-01-2019','22-01-2019','02-02-2019','03-02-2019','24-02-2019');
上面是我的数组,我想按周对日期进行分组,以便可以在报表中正确显示它们。所以会像这样:
Array
(
[31-12-2018/06-01-2019] => Array // this is based in calendar week
(
[0] => 01-01-2019
[1] => 02-01-2019
[2] => 05-01-2019
)
[21-01-2019/27-01-2019] => Array
(
[0] => 22-01-2019
)
[28-01-2019/03-02-2019] => Array
(
[0] => 02-02-2019
[1] => 03-02-2019
)
[18-02-2019/24-02-2019] => Array
(
[0] => 24-02-2019
)
)
答案 0 :(得分:3)
此代码将执行您想要的操作。它将每个日期值转换为DateTime
对象,找到该日期的一周的开始和结束,然后将该值推入一个新的数组,该数组由周的开始和结束值索引:
$date = array('01-01-2019','02-01-2019','05-01-2019','22-01-2019','02-02-2019','03-02-2019','24-02-2019');
$dates = array();
foreach ($date as $d) {
$od = date_create_from_format('d-m-Y', $d);
// get start and end of this week
$sow = $od->sub(new DateInterval('P' . ($od->format('N') - 1). 'D'))->format('d-m-Y');
$eow = $od->add(new DateInterval('P6D'))->format('d-m-Y');
$dates["$sow/$eow"][] = $d;
}
print_r($dates);
输出:
Array (
[31-12-2018/06-01-2019] => Array (
[0] => 01-01-2019
[1] => 02-01-2019
[2] => 05-01-2019
)
[21-01-2019/27-01-2019] => Array (
[0] => 22-01-2019
)
[28-01-2019/03-02-2019] => Array (
[0] => 02-02-2019
[1] => 03-02-2019
)
[18-02-2019/24-02-2019] => Array (
[0] => 24-02-2019
)
)