Use variable outside of loop

i’m pretty sure that it is a super stupid question, but i can’t wrap my head around it.

my setup:

parent
  child
     structured field with tags

while displaying the the parent-site i use the following code

  <ul class="projects__entries">
    <?php foreach($page->children()->visible()->filterBy('translationComplete', '1') as $child): ?>
      <li class="projects__entry" data-sort="<?= $child->title() ?>" >
        <?php $stations = $child->stations()->toStructure();
        foreach($stations as $station): ?>
            <div class="media-wrapper filterItem <?php foreach ($station->station_tags()->split(',') as $tag):?><?= str::slug($tag) ?><?= ' '?><?php endforeach ?>"></div>
        <?php endforeach ?>
       </div>
     </div>
    </li>
  <?php endforeach ?>
</ul>

now i’m tryin to add <?= str::slug($tag) ?> to the <li>. i know i can’t access the $tag outside the foreach – but as i said… i can’t find a solution to access it. or is the solution simpy to set up another loop for the tag inside of the <li class="" > – would be kind of dirty and confusing?

Do I understand this correctly, you want all the tags of all the stations in the class attribute of the li tag?

yes:

each li represents one child-page. each child-page contains several stations. each station can hold several tags. and all the tags of all the stations contained in one child-page should be the class attribute of the li tag.

Yes, you have to use the foreach loops twice:

<ul class="projects__entries">
  <?php foreach($page->children()->visible() as $child): ?>
    <?php 
      $stations = $child->stations()->toStructure(); 
      $allTags = [];

      foreach($stations as $station) {
        foreach($station->station_tags()->split(',') as $tag) {
          $allTags[] = $tag;
        }
      } 
    ?>
    <li class="projects__entry <?= implode(' ', $allTags) ?>" data-sort="<?= $child->title() ?>" >
      <?php foreach($stations as $station): ?>
        <div class="media-wrapper filterItem <?php foreach ($station->station_tags()->split(',') as $tag):?><?= str::slug($tag) ?><?= ' '?><?php endforeach ?>"></div>
      <?php endforeach ?>
       </div>
     </div>
    </li>
  <?php endforeach ?>
</ul>
1 Like

is it possible to apply str::slug() on the $allTags array?

Of course:

$allTags[] = str::slug($tag);