2014-12-02 23 views
0

我發現這個questions這有助於我與我在做什麼顯示隨機圖像,但我快到問題是 - 我不斷收到未定義的索引錯誤此$images = glob($imagesDir. '*.{jpg,jpeg,png,gif}', GLOB_BRACE);從目錄使用PHP

這裏我完整的代碼(這是一個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設置爲隨機然後顯示在隨機目錄中隨機圖像,但像我上面說過,我一直收到一個未定義的索引錯誤。

有沒有人看到我在做什麼和我爲什麼會收到此錯誤有什麼問題?

+1

你能發佈錯誤消息嗎? – FlyingPiMonster 2014-12-02 22:35:38

+1

他說,它的未定義索引錯誤 – meda 2014-12-02 22:36:44

+0

通常錯誤信息不僅僅是「undefined index error」,雖然 – FlyingPiMonster 2014-12-02 22:37:58

回答

1

幾點建議:

這時並不需要如水珠會返回一個數組:

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

看到http://php.net/manual/en/function.glob.php

這將導致一個警告(但不是錯誤),如果水珠先前返回的假:

$avatar = array_pop($images); 

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

如果您確保在手冊中檢查返回類型,您將知道在代碼中檢查什麼。

如果(empty($var))很好,因爲它檢查false,null或未定義而不拋出錯誤。

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

你的錯誤消息不應該由水珠線造成的,它實際上可能是從這樣的:

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 

你錯誤應該有一個行號。檢查那條線和它之前的線。

+0

感謝您的建議。今天早上它開始自己的工作,但如果有更好的方法來寫它,我想這樣做。我明白你要求我改變,但我不知道如何去做。你能給個例子嗎? – iamthestreets 2014-12-03 14:06:29

+0

我用更清晰的例子更新了評論。 – 2014-12-03 16:21:15