3
\$\begingroup\$

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) < 1)
        return $byVendor;
    $vendor   = $rows[0]->AMVEND;
    $i = 0;
    foreach ($rows as $row ) {
        $currentVendor = $row->AMVEND;
        if ($currentVendor != $vendor)
            $i++;
        $byVendor[$i][] = $row;
    }
    return $byVendor;

Code used in the view:

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

        </tr>
    @endforeach
    </thead>
    <tbody>
    </tbody>
</table>
@endforeach
@endsection
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Review! We're glad that you found this site to help you improve your code. I hope you get some good reviews! \$\endgroup\$
    – Phrancis
    Feb 2, 2015 at 21:35

1 Answer 1

1
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.