DaOneRom
DaOneRom

Reputation: 294

Use all the items from an array inside @foreach of @foreach

I am struggling over a difficulty on how to display my items from an array inside @foreach. And inside of that is another @foreach. The first one successfully displays all the items. But the second @foreach loops only on a single item. See codes below inside Controller...

Public function home(){
     $images = [
          'img/1.jpg',
          'img/2.jpg',
          'img/3.jpg'
     ];
     $lists = [
          '垂钓鲫鱼技巧之饵料配方',
          '春季钓鲫鱼用饵配方的选择与使用',
          '早春钓鲫鱼该用什么类型的饵料?',
     ];

     return view('/', [
          'images' => $images,
          'lists' => $lists
     ]);
}

Then inside the view...

<div class="image-list">
     @foreach ($images as $image)
          <div class="img-content medium d-block f-l">
               <div class="img-container">
                    <a href="#" class="d-inline-block">
                        <img src="{{ asset($image) }}" alt="">
                    </a>
                    @foreach ($lists as $list)
                        <span class="d-block">{{ $list }}</span>
                    @endforeach
               </div>
          </div>
     @endforeach
</div>

The list inside the second @foreach just keeps repeating the same single item. Please help and respect. Thank you all!

Upvotes: 0

Views: 116

Answers (1)

Rick Calder
Rick Calder

Reputation: 18695

So element 1 of the images should have element 1 of the lists and so on correct? Don't do the lists in a loop, just echo out the one you need.

This should work. Not tested though.

<div class="image-list">
     @foreach ($images as $indexKey=>$image)
          <div class="img-content medium d-block f-l">
               <div class="img-container">
                    <a href="#" class="d-inline-block">
                        <img src="{{ asset($image) }}" alt="">
                    </a>
                    <span class="d-block">{{ $list[$indexKey] }}</span>
               </div>
          </div>
     @endforeach
</div>

Upvotes: 1

Related Questions