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

时间:2014-12-02 22:34:51

标签: php

我发现这个questions可以帮助我完成我正在做的事情,但我遇到的问题是 - 我一直收到此$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设置为Random,则显示Random目录中的随机图像,但就像我上面说的那样,我不断收到未定义的索引错误。

有没有人看到我在做什么有什么问题以及为什么我会收到这个错误?

1 个答案:

答案 0 :(得分:1)

一些建议:

这不是必要的,因为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))很好,因为它会检查false,null或undefined而不会抛出错误。

此外,由于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

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