1

我有一个 $events 对象,它使用 Laravel 4 中的查询生成器从我的数据库中的各种表中获取一堆结果。请参见此处http://paste.laravel.com/qIj

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

任何想法如何最好地实现这一目标?干杯。

4

2 回答 2

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
于 2013-05-07T11:23:10.380 回答
0

这有帮助吗?我不熟悉查询生成器,但你能从它开始的那一周过去吗?

在 PHP 4 中获取本周星期一的日期

于 2013-05-07T09:53:44.560 回答