douqiang4501 2017-08-03 10:04
浏览 80

星期六到星期五的星期几组的日期组的PHP数组

I've an array containing items. Each item has a title and startdate. Now i want to group these items by week. If i look at the documentation, the format->('W') weeks starts on monday. I need to change this to saturday.

        $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
        ],
    ];

I've something like this but its not working correctly

        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'],
            ];
        }
  • 写回答

2条回答 默认 最新

  • dtqi87613 2017-08-03 10:45
    关注

    Try the following code

    $startDate = \DateTime::createFromFormat('Y-m-d', $item['startdate']);
    $week = intval($startDate->format('W'));
    $day = intval($startDate->format('N'));
    
    $a = ($day < 6 ) ? $week-1 : $week;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)