周开始在Laravel 4

时间:2013-05-07 09:46:46

标签: php date laravel laravel-4 weekday

我有一个$ events对象,它使用Laravel 4中的Query Builder从我的数据库中的各个表中获取大量结果。请参阅此处http://paste.laravel.com/qIj

我想将这些结果分成一周开始,所以当我在视图中输出它时,它会根据事件表的start_date字段中的信息按周分组所有内容。

任何想法如何最好地实现这一目标?欢呼声。

2 个答案:

答案 0 :(得分:4)

我通常做这样的事情:

<?php
// Event model
public function getAllByWeek() {
    $events = static::orderBy('created_at', 'DESC')->get();
    $orderedEvents = array();

    foreach ($events as $event) {
        $date = new \DateTime($event->created_at);
        $weekCategory = $date->format('oW');
        $weekFormatted = $date->format('W');

        if ( ! array_key_exists($weekCategory, $orderedEvents)) {
            $orderedEvents[$weekCategory] = (object) array(
                'week' => $weekFormatted,
                'events' => array(),
            );
        }

        $orderedEvents[$weekCategory]->events[] = $event;
    }

    return $orderedEvents;
}

// Controller
$orderedEvents = Event::getAllByWeek();

// View
@foreach ($orderedEvents as $eventsHolder)

    {{ $eventsHolder->week }}

    @foreach ($eventsHolder->events as $event)

        // content output

    @endforeach

@endforeach

答案 1 :(得分:0)

这有帮助吗?我不熟悉查询构建器,但是你可以通过它开始的一周吗?

Get date of Monday in current week in PHP 4