在PHP中按日期对MySQL结果进行分组

时间:2015-04-25 08:08:05

标签: php mysql laravel eloquent laravel-5

所以我发现自己陷入了困境。我正在使用Laravel与MySQL一起为我的工作建立一个打孔/打孔网站。我之所以这样做是因为我讨厌那里的其他解决方案,部分是因为我想学习Laravel框架。我已经整理了冲压系统,一切正常,但现在我试图让仪表板设置在哪里列出当前和过去的用户拳。

如果用户在一天内多次打入和关闭,我想只显示一次日期以使事情看起来更清洁。

以下是我的意思的一个例子: Example table

现在,左侧的所有列都包含日期。

现在我是Laravel的新手,所以我知道这段代码并不是很好,而且我还有一些修复工作要做,但是有人可以帮我弄清楚如何将结果分组,如上图所示?

这是我目前的代码:

<?php $punches = App\User::find(Auth::user()->id)->punches()->orderBy('created_at', 'desc')->get() ?>
    <table class="table table-striped table-bordered">
        <th>Date</th>
        <th>In Time</th>
        <th>Out Time</th>
        @foreach($punches as $punch)
            <tr>
                <td>{{Carbon\Carbon::parse($punch->created_at)->format('F d, Y')}}</td>
                <td>{{Carbon\Carbon::parse($punch->inPunch)->format('h:i A')}}</td>
                <td>{{Carbon\Carbon::parse($punch->outPunch)->format('h:i A')}}</td>
            </tr>
        @endforeach
    </table>

欢迎提出任何问题。我会尽快回答。拜托,谢谢!

1 个答案:

答案 0 :(得分:2)

您似乎不需要对它们进行分组。这只是显示日期何时发生变化的问题。每次新的$ punch日期不同于之前的$ punch显示它。

<?php $current_date = null; ?>
@foreach($punches as $punch)
  <tr>
    <td>
      @if ($punch->created_at)->format('F d, Y') != $current_date)
        <?php $current_date = $punch->created_at)->format('F d, Y'); ?>
        {{ $current_date }}
      @endif
    </td>
    <td>{{Carbon\Carbon::parse($punch->inPunch)->format('h:i A')}}</td>
    <td>{{Carbon\Carbon::parse($punch->outPunch)->format('h:i A')}}</td>
  </tr>
@endforeach

我很抱歉刀片模板中的'丑陋'php代码。我想展示提出的解决方案的想法。

相关问题