2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravelのbladeにて、多重のforeachを使って複数の配列を元にhtmlを表示する

Posted at

実現したいこと

例えば不動産システムを例にした時に、複数の配列の情報を元に、
「物件情報のjsonを参考にリストで表示し、isLivedがtrueのものだけ 背景の色をグレーにしたい」
に近いことがしたいと思った時、$loopがとても便利だったのでメモ。

sample.json
                "price": [{
                    "place_1": 60000,
                    "place_2": 85000,
                    "place_3": 90000,
                    "place_4": 80000,
                    "place_5": 80000,
                    "place_6": 100000
                }],
                "isLived": [{
                    "place_1": null,
                    "place_2": null,
                    "place_3": null,
                    "place_4": null,
                    "place_5": null,
                    "place_6": true
                }]

実装例

sample.blade.php
        @foreach ( $sample['rental_apartments'] as $rental_apartment )
          <div class="h40 w-100 border">
              <div class="d-flex flex-wrap">
                @foreach ($rental_apartment["isLived"][0] as $rental_apartment_isLived)
                  @if ($rental_apartment_isLived !== null)
                  <div class="bg-grey">
                    @foreach ($rental_apartment["depth"][0] as $rental_apartment_price )
                      @if ($loop->parent->index === $loop->index)
                          {{ $rental_apartment_price }}
                      @endif
                    @endforeach
                  </div>
                  @elseif($rental_apartment_isLived === true)
                  <div>
                    @foreach ($rental_apartment["price"][0] as $rental_apartment_price )
                      @if ($loop->parent->index === $loop->index)
                          {{ $rental_apartment_price }}
                      @endif
                    @endforeach
                  </div>
                  @endif
                @endforeach
              </div>
          </div>
        @endforeach

アプローチとしては、
多重のforeachの中で、
$loop->parent->index === $loop->index

を突き合わせることで、同じ順番の要素の時だけが判定されるようにしている。

そもそもjson構造はこうあるべきでないとか、書き方が冗長なんじゃないかとか、、もっとループの計算量は少なくできるんじゃないかとか、色々と余地がありそうだが一旦公開してみる。

参考記事

【Laravel】foreach文における$loop変数に感動した

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?