yinshiro
yinshiro

Reputation: 159

How to: foreach without affecting every row?

Is there a way to do a foreach on for example your products and sort this by their category_id and show the category name above the products. (I'm using laravel 4 as framework)

Example what the output should look like:

Chairs

 wooden chair number 1

 pretty chair number 1

 pretty chair number 2

Doors

 tall door number 1

 white door number 1

Key question: How can i make a foreach without having the categoryname above each row ?

Hopefully i made my question/problem clear and can someone help me out!

This is what i got so far:

Though, when i do my foreach in the blade i will get the error: " Undefined index "

The foreach i used in my controller:

    foreach($results as $result) {
        $category[$result->category_id][] = $result;
    }

My foreach in the blade:

    @foreach ($category as $key => $product)
        <tr>
            <td>{{ $product[$key]['created_at'] }}</td>
            <td>{{ $product[$key]['order_id'] }}</td>
            <td>{{ $product[$key]['name'] }}</td>
        </tr>
    @endforeach

Upvotes: 0

Views: 157

Answers (2)

vertazzar
vertazzar

Reputation: 1063

you are attempting to use category_id to fetch $product from $products, which is array with 0-X indexes. for sake of simplicity i will ignore html formatting and syntax since i never used framework mentioned...

@foreach ($category as $key => $products)
       echo 'Category #', $key

       @foreach ($products as $product)
       <tr>
        <td>{{ $product['created_at'] }}</td>
        <td>{{ $product['order_id'] }}</td>
        <td>{{ $product['name'] }}</td>
       </tr>
      @endforeach

@endforeach

Upvotes: 1

hamobi
hamobi

Reputation: 8130

not completely sure i understand the question. but if im trying to organize an array.. i might use a conditional statement inside the foreach loop. I'm not sure your question is very clear.. see if this helps at all

foreach($results as $result) {

    // just an example.. i narrow down what I push into my category array
    if($result->type == 'whatever'){
        $category[$result->category_id][] = $result;
    }

}

Upvotes: 0

Related Questions