Ok… I’ve tried to achieve this using only kirby helpers or the toolkit API… and failed miserably.
I have a simple structure field with some (unknown) number of entries:
Intros:
-
category: cwk
title: My title 1
link: events/test-3000
-
category: school
title: My title 2
link: events/test2
-
category: shop
title: My title 3
link: events/test-9000
...
I’ve tried everything I could find in the docs… i.e.:
It trows “Warning: Illegal string offset ‘category’ in…” when I try to access any associative array’s elements like “category”… it also retrieves the first letter of each element along with these errors.
You can fetch a single element of the array like this:
$number = 0;
$intro[$number]['category'];
So you could use a random number from an array of numbers between 0 and number of elements in the array - 1. Don’t know if this is the most elegant way, but at least it works.
Thanks @HeinerEF, either I didn’t get it… or it doesn’t works.
Before posting here I fiddled with toStructure()… but it expects a string (yaml) and there’s no way to shuffle it (that I know)… that’s why I was converting it to an Array and shuffling it before extracting one entry (the first).
Kinda lame, but I thought it’d work…
I event tried to convert it back to yaml before using the toStructure():
But actually, I don’t quite know where your problem actually is? So the shuffling works alright as outlined above? If so, you don’t need to shuffle the numbers and using 0 for the first element should suffice?
already gives you what you want and all you would have to do, is echo the category or whatever like so:
<?php echo $firstIntro['category']; ?>
The thing that does not make sense to me, is that you want to loop through an array that only contains one element because in your code
$randIntros = a::shuffle( yaml($page->intros()) );
//here you shuffle all the elements in the array
$firstIntro = a::first($randIntros);
//here you pick the first of these elements, so there will never be more than one element in this array