2016-02-22 19 views
0

我有一個文件夾中的圖像,我想隨機化圖像顯示爲完整背景圖像,同時顯示當前背景圖像的文本描述顯示?代碼如下所示。如何綁定或循環隨機背景圖像到文本

<?php 
    function displayBackground() 
    { 
    $dir = 'control/uploads/image/home_bg/'; 
    $cnt = 0; 
    $bgArray= array(); 

    /*if we can load the directory*/ 
    if ($handle = opendir($dir)) { 

    /* Loop through the directory here */ 
    while (false !== ($entry = readdir($handle))) { 

    $pathToFile = $dir.$entry; 
    if(is_file($pathToFile)) //if the files exists 
    { 

    //make sure the file is an image...there might be a better way to do this 
    if(getimagesize($pathToFile)!=FALSE) 
    { 
     //add it to the array 
     $bgArray[$cnt]= $pathToFile; 
     $cnt = $cnt+1; 

    } 

    } 

} 
//create a random number, then use the image whos key matches the number 
$myRand = rand(0,($cnt-1)); 
$val = $bgArray[$myRand]; 

    } 
    closedir($handle); 
    echo('"'.$val.'"'); 

    } 


    ?> 
+1

到目前爲止您嘗試過什麼?請閱讀[_我如何問一個好問題_](http://stackoverflow.com/help/how-to-ask) – Oka

+0

我曾嘗試使用PHP來隨機化背景圖片,但不知道如何輸出文字描述爲當前圖像顯示。 –

+0

然後顯示你已經嘗試了什麼,以及你卡在哪裏。沒有人可以幫助你看到他們看不到的代碼。 – Oka

回答

1

我不同意Phillip的解決方案。使用一個路徑作爲文件名並且有一個文本文件可以產生很多文件。將信息放入同一結構數據的易於訪問的地方是最佳實踐。

您需要將信息存儲在某處(文件或數據庫表),並獲取相應的文本說明。 [您也可以在您的代碼中對其進行硬編碼,但我不建議]

如果您沒有很多圖像文件,我建議您只需將信息放入.json文件中類似這樣的格式:

[{"file":"control/uploads/image/home_bg/image1.jpg","description":"This is the first image"}, 
{"file":"control/uploads/image/home_bg/image2.jpg","description":"This is the second image"}] 

然後在你的PHP代碼,你可以做json_decode(file_get_contents($path_of_this_json_file));和獲得的信息的數組。

如果你想隨機顯示這些,只需使用php隨機函數從數組中選擇一個元素並使用它。

0

您需要將文本描述存儲在某處,並用文件名索引。

這可以是不同的.txt文件[file-name-of-image].txt或者您可以使用一個數組,其中的索引是文件名和值的說明。

這樣,您只需要圖像文件名即可獲取描述並顯示它。