Formatting database results to be consumed as multiple tables by the view In the code below, $rows is the result of database query. In the view that consumes this, I need to break the results into a separate table for each vendor. 

The below creates a structure that allows this in the template, but it seems like a clunky way of doing it. Advice on how to improve it?

    $byVendor = [];
    if (sizeof($rows) &lt; 1)
        return $byVendor;
    $vendor   = $rows[0]-&gt;AMVEND;
    $i = 0;
    foreach ($rows as $row ) {
        $currentVendor = $row-&gt;AMVEND;
        if ($currentVendor != $vendor)
            $i++;
        $byVendor[$i][] = $row;
    }
    return $byVendor;


Code used in the view:

@section('content')
@foreach($vendors as $vendor)
&lt;table class="table"&gt;
    &lt;caption&gt;{{$vendor[0]-&gt;AMNAME}}&lt;/caption&gt;
    &lt;thead&gt;
        &lt;tr&gt;
            &lt;th&gt;Date/Time&lt;/th&gt;
            &lt;th&gt;PO Number&lt;/th&gt;
            &lt;th&gt;Item&lt;/th&gt;
            &lt;th&gt;Qty&lt;/th&gt;
        &lt;/tr&gt;
    @foreach($vendor as $item)
        &lt;tr&gt;
            &lt;td&gt;{{$item-&gt;CREATED_AT}}&lt;/td&gt;
            &lt;td&gt;{{$item-&gt;SOURCE}}&lt;/td&gt;
            &lt;td&gt;{{$item-&gt;ITEM}}&lt;/td&gt;
            &lt;td&gt;{{$item-&gt;QTY}}&lt;/td&gt;

        &lt;/tr&gt;
    @endforeach
    &lt;/thead&gt;
    &lt;tbody&gt;
    &lt;/tbody&gt;
&lt;/table&gt;
@endforeach
@endsection
If you add a group by clause to your query on the AMVEND column, you won't have to do any looping before you pass the data to the view. You can simply detect when the vendor changes in the view's foreach loop.