Random entry from structure (workaround)

Hey there. I noticed @texnixe opened this issue up on GitHub back in March, but while it’s in the hopper, I’m wondering if someone could help me solve this another way. Basically, here’s the idea:
I have a structure field set up that asks for a couple pieces of information (name, image, etc), and what I want to do is have it so, on page load, the site picks a random entry in the structure and displays that information.

I’ve tried various versions of $page->structure_field()->shuffle()->toStructure()->first();, (with ->shuffle() moved to different spots) but either it doesn’t work (breaks the page) or simply displays the first one in the structure (ignoring the shuffle).

Could I get a pointer of an alternate way to solve this? I can count the number of fields in that structure and generate a random number based on that, but I’m not sure how to select that specific thing out of the structure.

Something like…

$luckies = $page->lucky_people()->toStructure()->count();
$r = rand(1, $luckies);
$randomLucky = $page->lucky_people()->toStructure()->children($r);

…except not that, because that’s failing to work.

You could try the nth() method. As an alternative, use the toYaml() method instead of toStructure() and then shuffle the resulting array. I had the same problem a while ago, can’t remember how I solved it in the end.

1 Like

There it is! nth() was what I was looking for. Final version, for those that find this page…

    $luckies = $page->lucky_people()->toStructure()->count() - 1;
    $r = rand(0, $luckies);
    $randomLucky = $page->lucky_people()->toStructure()->nth($r);

now you can call on $randomLucky however you like, ex:
<header style="background-image:url(<?php echo $randomLucky->background_mobile()->toFile()->url(); ?>)">

Edited to compensate for 0 index.

Shuffling structure collections will finally work in Kirby 2.3.1. :slight_smile: