How to access a field inside a structure?


So I have a structure



I want to access ‘residentsInfo’ structure field ‘countries’ so i can count how many different countries there are (without counting same country twice).

Firstly i can’t even access my field inside a structure…

If I try this:

i get nothing:
Screenshot 2023-02-21 at 17.47.11

And if I try this:

I get ‘Call to a member function count() on null’ error.

If someone would lend me a hand I would really appreciate it, thank you!

In the future, please don’t post screenshots of code, but code blocks to work with.

You have to loop through your residents variable, only then can you access the fields of each individual item. See the structure field documentation in the reference.

Okay, sorry for that!

So far i managed to get and display each archive’s countries without duplications:
Screenshot 2023-02-22 at 11.48.29

With this code:

<?php $archives = site()->find('archives')->children()->listed()->sortBy('title', 'desc') ?>
<?php foreach ($archives as $archive): ?>
  <a href="<?= $archive->url() ?>" class="archives--item">
  <div class="archives--item-header">
          <?php $residents = $archive->residentsInfo()->toStructure() ?>
          <p class="info-text"><?= $residents->count() ?> rezidentai</p>
          <p class="info-text">
                  <?php $countries = $residents->pluck('countries', ',', true); ?>
                  <?php foreach ($countries as $country): ?>
                          <?= $country ?>
                  <?php endforeach; ?>

But if i try to count countries like this:

<?= $country->count() ?>

I get an error Call to a member function count() on string

And this:

<?= $countries->count() ?>

Throws me Call to a member function count() on array

What i want is instead of displaying “usa lt en” countries it should return number 3, because there is such quantity of different countries inside an archive. What am I doing wrong…?

$countries is an array (as result of pluck) so to could use count($countries)

1 Like

Thank you very much for your effort, that was it!