使用随机函数,但它显示重复

发布于 2025-01-28 05:06:29 字数 472 浏览 2 评论 0原文

我正在使用树枝中的随机函数,它正在随机化所需的图像,但正在重复徽标。我该如何做到这一点,以便不重复这些图像,但仍是随机的?

这是我的代码

{% set listItems = block.logos %}
    {% for item in listItems %}
        {% set item = random(listItems) %}
{% endfor %}

块。logos是指我在块称为徽标中实现的徽标。块中有一个字段,我可以在块中添加多个图像/徽标。我有大约20个徽标。

我附上了一张照片以参考该问题。

I am using the random function in twig and it is randomizing the images I need but it is repeating the logos. How can I make it so that the images are not repeated but are still randomized?

this is my code

{% set listItems = block.logos %}
    {% for item in listItems %}
        {% set item = random(listItems) %}
{% endfor %}

block.logos refers to the logos that i have implemented in block called logos. There is a field in the block in which i can add multiple images/logos in the block. i have about 20 logos.

Ive attached a photo for reference of the issue.
enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花间憩 2025-02-04 05:06:29

您可以使用php array_rand函数。

array_rand($ listItems,1);

如果您的数组是键值数组,并且您的需要,则使用返回的键作为获取图像的索引。

$index = array_rand($listItems, 1);
print_r($listItems[$index]);

You can use the PHP array_rand function.

array_rand($listItems, 1);.

If your array is a key value array and your need the value use the returned key as index for get the image.

$index = array_rand($listItems, 1);
print_r($listItems[$index]);
国产ˉ祖宗 2025-02-04 05:06:29

如果我正确理解这一点:您有一个图像列表,并且希望以随机顺序显示它们,而不显示两次相同的图像。

理想情况下,您可以基于PHP函数来实现自定义的树枝函数: shuffle 。但是,对于快速解决方案,您可以随机对数组进行整理。

{% set listItems = block.logos|sort((a, b) => random() <=> random()) %}
{% for item in block.logo %}
    {{ item }}
{% endfor %}

If I understand this correctly: you have a list of images, and want to display them in a random order without displaying the same image twice.

Ideally you could implement a custom twig function based on the php function: shuffle. However for a quick solution, you could randomly sort an array.

{% set listItems = block.logos|sort((a, b) => random() <=> random()) %}
{% for item in block.logo %}
    {{ item }}
{% endfor %}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文