Symfony:随机播放阵列

时间:2016-08-18 08:56:58

标签: php arrays symfony shuffle

我试图从阵列中的目录中获取所有图像,然后将其洗牌,然后在Symfony的视图中显示它。

例如:

/images/theme/404/01.gif

/images/theme/404/02.gif

/images/theme/404/03.gif

是图像,但我不知道有多少图像。我尝试将这些图像随机播放以显示它。

我这样做了:

控制器

public function showAction()
{
    $dir = $this->get('kernel')->getRootDir() . '/../web/images/theme/404/';
    $dh  = opendir($dir);
    $errorFiles = array();
    $errorFilesShuffled = shuffle($errorFiles);
    while (false !== ($filename = readdir($dh)))
        if ($filename != '.' && $filename != '..' && $filename[0] != '.')
            $errorFilesShuffled[] = $filename;

    return $this->render('errors/show.html.twig', [
                'gifs' => $errorFilesShuffled
    ]);
}

查看

{% for image in gifs %}
    <div class="clearfix mosaicflow">
        <div class="mosaicflow__item">
            <img src="{{ asset('/images/theme/404/'~image) }}" />
        </div>
    </div>
{% endfor %}

我收到此错误错误:Warning: Cannot use a scalar value as an array

修改

使用此控制器,我不再有错误。

控制器

public function showAction()
{
    $dir = $this->get('kernel')->getRootDir() . '/../web/images/theme/404/';
    $dh  = opendir($dir);
    $errorFiles = array();
    while (false !== ($filename = readdir($dh)))
        if ($filename != '.' && $filename != '..' && $filename[0] != '.')
            $errorFiles[] = $filename;

    $errorFilesShuffled = shuffle($errorFiles);

    return $this->render('errors/show.html.twig', [
        'gifs' => $errorFilesShuffled
    ]);
}

但我有另一个问题,我无法看到页面上的图像。当我检查HTML时,div <div class="clearfix mosaicflow">甚至不在这里。

1 个答案:

答案 0 :(得分:2)

如果你看一下函数shuffle()的定义,你会注意到每个引用都会给出数组,函数将返回一个布尔值。

所以

$errorFilesShuffled = shuffle($errorFiles);
if ($errorFilesShuffled === true)
    echo "HURRAY"; 

确实会回应 HURRAY

要使代码正常工作,您需要将其更改为:

shuffle($errorFiles); // The array will be given per reference
return $this->render('errors/show.html.twig', [
    'gifs' => $errorFiles
]);
相关问题