【问题标题】:PHP shuffle, multiple loopPHP shuffle,多重循环
【发布时间】:2016-05-30 14:56:31
【问题描述】:

我想在 PHP 中以相同的正确顺序随机播放 2 个循环(或函数)。

目前的代码如下:

<div class="overlay">

<?php

    // Get the list of all files with .jpg extension in the directory and save it in an array named $images
    $directory = "uploads/_gallery/*.jpg";

    // Create an array of images found in the uploads directory
    $images = glob($directory);

    // Randomise/shuffle the images
    shuffle($images);

    foreach( $images as $image ):
        if ($image) { ?>
            <div class="slide">
                <?php echo "<img src='" . $image . "'>"; ?>
            </div>
        <? }
    endforeach;

?>

&lt;/div&gt;

&lt;div class="grid"&gt;

<?php

    // Get the list of all files with .jpg extension in the directory and save it in an array named $images
    $directory = "uploads/_gallery/thumbs/*.jpg";

    // Create an array of images found in the uploads directory
    $images = glob($directory);

    // Randomise/shuffle the images
    shuffle($images);

    foreach( $images as $image ):

        if ($image) { ?>
            <figure class="unit_25">
                <?php echo "<img src='" . $image . "'>"; ?>
            </figure>
        <? }

    endforeach;

?>

&lt;/div&gt;

我尝试创建两个单独的图像数组并使用 Shuffle 合并它们,但没有成功。

【问题讨论】:

    标签: php


    【解决方案1】:

    我假设文件在两个目录中具有相同的名称。 所以洗牌$images 然后使用basename($images) 来获取文件名:

    $directory = "uploads/_gallery/*.jpg";
    $images = glob($directory);
    shuffle($images);
    
    
    // For full sized images
    foreach ($images as $image) {
        // Your stuff
    }
    
    // For thumbnails
    foreach ($images as $image) {
        $basename = basename($image);
        $thumbnailPath = "uploads/_gallery/thumbs/". $basename;
        // Your stuff
    }
    

    【讨论】:

    • 感谢@JesusTheHun 的快速回复(顺便说一句有趣的尼克)。我尝试了您的建议,但拇指正在加载最顶层的基本目录,而不是缩略图目录。我应该将每个 foreach 包装在一个函数中吗?
    • 你是不是复制了我的代码?因为我忘记了缩略图路径中的斜线(现在编辑)。查看 html 渲染时路径是否正确?如果是但它不起作用,那么我不明白你期望的结果
    • 回答你之前的问题:我意识到这可能是问题所在,拇指除了文件名_1_thumb.jpg之外还有相同的名称。是的,我确实在缩略图路径中添加了斜线
    • 所以,我重命名了图像并将其更改为:&lt;?php echo "&lt;img src='" . $image . "'&gt;"; ?&gt;&lt;?php echo "&lt;img src='" . $thumbnailPath . "'&gt;"; ?&gt;。它有效。谢谢一百万!
    猜你喜欢
    • 1970-01-01
    • 2017-03-02
    • 2012-04-01
    • 2021-12-13
    • 2012-02-28
    • 2011-08-07
    • 1970-01-01
    • 2015-03-21
    • 2013-10-10
    相关资源
    最近更新 更多