我有一个包含项目的数组。每个项目都有一个标题和开始日期。现在我想按周分组这些项目。如果我查看文档,格式 - >(' W') 星期一星期开始。我需要把它改成星期六。
$items = [
[ // friday
'title' => 'test',
'startdate' => '2016-03-18', // first group
],
[ // saturday
'title' => 'test',
'startdate' => '2016-03-19', // second group
],
[ // sunday
'title' => 'test',
'startdate' => '2016-03-20', // second group
],
[ // monday
'title' => 'test',
'startdate' => '2016-03-21', // second group
],
[ // saterday
'title' => 'test',
'startdate' => '2016-03-26', // third group
],
];
我有类似的东西,但它无法正常工作
foreach($items as $item) {
// group by week
$startDate = \DateTime::createFromFormat('Y-m-d', $item['startdate']);
$currectWeek = $startDate->format('W');
$saturday = 6;
$friday = 5;
$test = clone $startDate;
if($currectWeek !== 5){
$test->modify('last friday');
}
if($currectWeek !== 6){
$test->modify('next saturday');
}
$a = $test->format('W');
if(!isset($items_by_week[$a])){
$items_by_week[$a] = [];
}
$items_by_week[$a][] = [
'title' => $item['title'],
'date' => $item['startdate'],
];
}
答案 0 :(得分:0)
尝试以下代码
$startDate = \DateTime::createFromFormat('Y-m-d', $item['startdate']);
$week = intval($startDate->format('W'));
$day = intval($startDate->format('N'));
$a = ($day < 6 ) ? $week-1 : $week;
答案 1 :(得分:0)
分组为星期(星期六开始,星期五结束)。这是结果,使用了以下代码:
$theNewDate = new DateTime(date("Y-m-d"));
$theNewDate->add(new DateInterval('PT1814400S'));
/* I use 1814400 seconds just to demonstrate one way of adding 21 days */
/* You can just as easily use $theNewDate->add(new DateInterval('P21D')); */
$label .= '<br /><small>';
switch ( $method->method_id ) {
case 'free_shipping':
$label .= 'Est delivery date: ';
$label .= $theNewDate;
}
但是现在我也想在一周内分组。所以需要类似下面的输出
$byWeek = array();
foreach ($items as $item) {
$date = DateTime::createFromFormat('Y-m-d', $item['date']);
$firstDayOfWeek = 6; // Saturday
$difference = ($firstDayOfWeek - $date->format('N'));
if ($difference > 0) { $difference -= 7; }
$date->modify("$difference days");
$week = $date->format('W');
if(!isset($byWeek[$week])){
$byWeek[$week] = [];
}
$byWeek[$week][] = $item;
}
// result
Array
(
[31] => Array
(
[0] => Array
(
[title] => test 11
[date] => 2017-08-11
)
)
[32] => Array
(
[0] => Array
(
[title] => test
[date] => 2017-08-12
)
[1] => Array
(
[title] => test 222
[date] => 2017-08-12
)
[2] => Array
(
[title] => test 1
[date] => 2017-08-13
)
[3] => Array
(
[title] => test 2
[date] => 2017-08-14
)
)