Getting specific page children structure field

I have a page like this

Animals

  • Dog
  • Cat
  • Horse

Animals is the parent and under it are the children.

Now im trying to get the specific children, ex: Cat and inside the Cat has structure field.

how to do that?

You can use the page() helper function to retrieve any page by its URI. So, if you already know that you want the ‘animals/cat’ page, you can retrieve that page with page('animals/cat').

Once you have the page, you access its structure field just like you’d access any structure field - usually converting its content to a Structure object, or to an array:

// if you want a structure object
$struct = page('animals/cat')->my_struct_field()->toStructure();

// if you want an array
$struct = page('animals/cat')->my_struct_field()->yaml();

If you don’t already know the URI of the page - like, you don’t know whether it’s called ‘cat’, or ‘penguin’ or ‘lion’ - then you’ll probably need to use $page->children() to iterate through all the children of the parent page, and get the contents of the structure field of each child.

$parent = page('animals');
foreach($parent->children() as $subpage):
    $info = $subpage->my_struct_field()->toStructure();
    //...do what you need to do with the info
endforeach;

Keep in mind that the above code will result in an error ("Call to a member function field_name() on boolean) if the page does not exist (or is deleted or renamed later).

If you want to be on the save side:

$p = page('animals/cat');
$p? $items = $p->structure_field()->structure(): $items = null;
if($items) {
foreach($items $item):
  // do something
endforeach;

@luxlogica Thank you that works. But it lists all the structures from all children.

How to make it dynamic?

The chosen children will be based thru another structure field.

$pets = $page->pets_list()->toStructure();

     foreach ($pets as $pet) : 
          
     endforeach;

The code will depend on what is saved in the pets page structure field: the UID or the URI of those child pages?

the uri of the page

Pets-items: 

- pets_list: "cat"
- pets_list: "dog"
- pets_list: "horse"

That is the UID, not the URI, the URI would contain the full path of the page. Looks like your field is call pets_items, not pets_list.

Anyway, assuming that the current page is the parent of those animals:

<?php
$pets = $page->pets_items()->toStructure();

foreach($pets as $pet) : 
  $p = $page->children()->find($pet); //if the current page is not the parent of those animals: page('animals')->children()->find($pet)
    if($p):
      $items =  $p->structure_field()->structure();
      foreach($items as $item):
        // do stuff
      endforeach;      
    endif;
endforeach;

my saviour. thanks @texnixe