【问题标题】:Display random image from directory using php使用php显示目录中的随机图像
【发布时间】:2014-12-02 22:34:51
【问题描述】:

我发现这个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 目录中的随机图像,但就像我上面所说的,我不断收到未定义的索引错误。

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

【问题讨论】:

  • 你能发布错误信息吗?
  • 他说的是未定义的索引错误
  • 回显$images 并确保它看起来没问题。您可能需要更明确地说明照片的路径。
  • 顺便说一句,if(count($images)==0){ 没有任何意义,因为您已将$images 直接设置为空数组,因此该语句将始终返回 true。
  • $images 在您的glob() 之后是否包含任何内容? print_r($images); 我敢打赌你正在阅读一个不存在的目录。尝试使用dirname(__FILE__) 获取以/ 开头的完整路径

标签: php


【解决方案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

如果您确保检查手册中的返回类型,您就会知道要在代码中检查什么。

if (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

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

【讨论】:

  • 感谢您的建议。它今天早上开始自己工作,但如果有更好的方法来编写它,我想这样做。我明白你要求我改变什么,但我不知道该怎么做。能举个例子吗?
猜你喜欢
  • 2018-03-08
  • 2019-04-16
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 2012-09-21
  • 1970-01-01
  • 2021-10-14
  • 2012-08-06
相关资源
最近更新 更多