使用 php 显示目录中的随机图像


Display random image from directory using php

我发现了这个问题,这对我正在做的事情有所帮助,但我遇到的问题是 - 我不断收到这个$images = glob($imagesDir. '*.{jpg,jpeg,png,gif}', GLOB_BRACE);的未定义索引错误

这是我的完整代码(它是if/elseif的一部分(:

elseif($result['avatar_type'] == 'Random'){ 
    $images = array(); //Initialize once at top of script
    $imagesDir = 'avatar/random/';
    if(count($images)==0){
      $images = glob($imagesDir. '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
      shuffle($images);
      }
    $avatar = array_pop($images);
}

我正在尝试做的是,如果数据库将avatar_type设置为随机,则显示来自随机目录的随机图像,但就像我上面说的,我不断收到未定义的索引错误。

有没有人看到我正在做的事情有什么问题,为什么我会收到这个错误?

一些建议:

这不是必需的,因为 glob 将返回一个数组:

$images = array(); //Initialize once at top of script

见 http://php.net/manual/en/function.glob.php

如果 glob 之前返回 false,这将导致警告(但不是错误(:

$avatar = array_pop($images);

http://php.net/manual/en/function.array-pop.php

如果您确保在手册中检查返回类型,您将知道在代码中要检查的内容。

如果(empty($var))很好,因为它检查假、空或未定义而不会引发错误。

此外,由于array_pop返回最后一个元素,而 glob 可能会以相同的顺序返回元素,因此它不会像array_rand那样随机。

$avatarKey = array_rand($images, 1); //return 1 random result's key
$avatar = $images[$avatarKey]; //set the random image value (accessed w/ the rand key)

您的错误消息不应该是由 glob 行引起的,它实际上可能是来自这个:

elseif($result['avatar_type'] == 'Random'){ 

如果未在结果数组上设置avatar_type或结果数组为空,您将获得一个未定义的索引。

为了防止发生该错误,您应该在尝试访问avatar_type密钥之前检查数组是否存在:

函数示例:

function getRandomAvatar($result)
{
    if (empty($result) || empty($result['avatar_type'])) {
        return;  //quit execution if the data is bad
    }
    //rest of code here -
}

内联代码示例:

if (empty($result) || empty($result['avatar_type'])) {
    //do nothing, render an error, whatever - stops execution of the next statement
} else {
    //this code will only run if $result and $result['avatar_type 
    //are set and wont cause errors
    if ('$result['avatar_type'] == 'Random') {
        //do code here

您的错误应该有一个行号。 检查该行及其前面的行。