Ad

PHP / Laravel Foreach Loop - Show Only Items That Belongs To Same Headline

- 1 answer

I have a problem to view some data in the way I want to have it.

Here is a example of the array:

$items =         
       0 => [
               'name' => 'foo'
               'description' => 'bar'
               'url' => 'http://foobar.com'
               'headline' => 'Headline 1' 
            ],
       1 => [
               'name' => 'uni'
               'description' => 'corn'
               'url' => 'http://unicorn.com'
               'headline' => 'Headline 1' 
            ],

       2 => [
               'name' => 'awe'
               'description' => 'some'
               'url' => 'http://awesome.com'
               'headline' => 'Headline 2' 
            ],

And know I want to loop through the items array and want to show the headline at first and all items that have the same headline. If a item has another headline, I want to print out the other headline and the items that belongs to it.

Should look like that:

Headline 1 : <--- Items that do have this headline

name = foo
description = bar
url = http://foobar.com

name = uni
description = corn
url = http://unicorn.com

Headline 2 <----- items with a new headline

name = awe
description = some
url = http://awesome.com

I wansn't able to do that. Can someone help me there?

I've tried something like a for loop that checks the current headline with the next headline.

@for ($i = 0; $i <= count($items); $i++)
            <span>{{ $items[$i]['headline'] }}</span>
        @if($items[$i]['headline'] == $items[$i+1]['headline'])
        ..... 
        @ else .....
@endfor

But this haven't worked well

Thanks for your help and sorry because of my bad english!

Ad

Answer

Use laravel collections with groupby() method

$collection = collect($items);

$items= $collection->groupBy('headline');

$items->toArray();

The array will be splited by headline

From Laravel Docs https://laravel.com/docs/5.4/collections#method-groupby

Ad
source: stackoverflow.com
Ad