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)
        $byVendor[$i][] = $row;
    return $byVendor;

Code used in the view:

@foreach($vendors as $vendor)
<table class="table">
            <th>PO Number</th>
    @foreach($vendor as $item)

  • \$\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
    Commented Feb 2, 2015 at 21:35

1 Answer 1


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.


Your Answer

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

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