显示数组

时间:2015-12-05 15:02:26

标签: php arrays laravel

我使用Laravel作为我的框架,但它本身并不是一个laravel问题。从数组中,我试图显示每个月的结果,如下所示:

<table>
    <tr>
        <td>January</td>
    </tr>

    <tr>
        <td>First result for january</td>
        <td>Second result for january</td>
    </tr>

    <tr>
        <td>February</td>
    </tr>

    <tr>
        <td>First result for february</td>
        <td>Second result for february</td>
    </tr>
</table>

在我的控制器中,我得到的结果如下:

$results = Expense::whereBetween('date', array($start, $end))->get();

其中$start$end是我从输入中收集的日期,格式为YYYY-MM-DD

在我看来,我会像这样(示例)显示结果:

@foreach($results as $result)

    {!! $result->date !!} - {!! $result->expense !!} - {!! $result->amount !!}

@endforeach

但我希望在上面的例子中有它。因此,当我在输入中选择不同的月份时,也会更改视图,因此我无法对其进行硬编码。我基本上需要更改我的foreach以显示一个月,所有结果都来自该月下方,然后显示下一个一个月,等等。

向正确的方向轻推会有所帮助。

1 个答案:

答案 0 :(得分:2)

我会使用Laravel Collections methods对结果进行分组:

$results = Expense::whereBetween('date', array($start, $end))->get();
$results = $results->groupBy(function($expense) 
{
    return Carbon\Carbon::parse($expense->date)->month;
});

然后您将得到以下格式的结果:

=> Illuminate\Database\Eloquent\Collection {#2708
  all: [
    1 => Illuminate\Database\Eloquent\Collection {#1427
      all: [
        App\Expense {#1410 …27},
        App\Expense {#3077 …27},
        App\Expense {#1408 …27},
        ...
      ],
    },
    2 => Illuminate\Database\Eloquent\Collection {#1428
      all: [
        App\Expense {#1310 …27},
        App\Expense {#3377 …27},
        App\Expense {#1308 …27},
        ...
      ],
    },
    3 => Illuminate\Database\Eloquent\Collection {#1429
      all: [
        App\Expense {#1810 …27},
        App\Expense {#3877 …27},
        App\Expense {#1808 …27},
        ...
      ],
    },
    ...
  ],
}

每个密钥代表一个月号。