使用php显示目录中的随机图像
我发现这对我的工作很有帮助,但我遇到的问题是-我一直在为这个使用php显示目录中的随机图像,php,Php,我发现这对我的工作很有帮助,但我遇到的问题是-我一直在为这个$images=glob($imagesDir.*.{jpg,jpeg,png,gif}',glob_BRACE)获取未定义的索引错误 以下是我的完整代码(它是if/elseif的一部分): 我试图做的是,如果数据库将avatar_类型设置为Random,然后显示来自Random目录的随机图像,但是就像我上面所说的,我不断得到一个未定义的索引错误 有人看到我所做的有什么错误吗?为什么我会收到这个错误?一些建议: 这不是必需的,因为glo
$images=glob($imagesDir.*.{jpg,jpeg,png,gif}',glob_BRACE)获取未定义的索引错误代码>
以下是我的完整代码(它是if/elseif的一部分):
我试图做的是,如果数据库将avatar_类型设置为Random,然后显示来自Random目录的随机图像,但是就像我上面所说的,我不断得到一个未定义的索引错误
有人看到我所做的有什么错误吗?为什么我会收到这个错误?一些建议:
这不是必需的,因为glob将返回一个数组:
$images = array(); //Initialize once at top of script
看
如果glob先前返回false,这将导致警告(但不是错误):
$avatar = array_pop($images);
如果您确保检查手册中的返回类型,您将知道在代码中检查什么
如果(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_类型密钥之前检查阵列是否存在:
功能示例:
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
您的错误应该有一个行号。检查那一行和它前面的那一行。你能发布错误消息吗?他说了,它的未定义索引错误会呼出$images
,并确保它看起来正常。您可能需要更明确地说明照片的路径。顺便说一句,如果(count($images)==0){
没有任何意义,因为您已将$images
直接设置为空数组,因此此语句将始终返回true。$images
是否在glob()
之后包含任何内容?打印($images)
我敢打赌您正在读取一个不存在的目录。请尝试使用dirname(_文件__)
以/
开始获取完整路径,感谢您的建议。它今天早上开始自己工作,但如果有更好的方法编写它,我希望这样做。我理解您要求我更改的内容,但我不确定如何做。您能举个例子吗?
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