簡體   English   中英

如何在div中顯示隨機選擇的圖像?

[英]How to display randomly selected images inside a div?

我正試圖從dir中顯示兩個隨機選擇的圖像

而不是圖像,顯示img.names

$dir    = 'memb_area/captcha/imgs/';
$files = scandir($dir);
$rand_keys = array_rand($files, 2);
echo $files[$rand_keys[0]] . "\n";
echo $files[$rand_keys[1]] . "\n";  

還嘗試過:

echo '<img src="memb_area/captcha/imgs">' + 'echo $files[$rand_keys[0]] . "\n";'

並且 - 是否可以在頁面上的單獨div中打印這些圖片?

+不是有效的PHP連接字符。 . 是。 通過使用+ ,您實際上是在添加這兩個字符串,當轉換為整數時,等於0

這一行:
echo '<img src="memb_area/captcha/imgs">' + 'echo $files[$rand_keys[0]] . "\\n";'

應該是:(更新)
echo "<img src=\\"memb_area/captcha/imgs/".$files[$rand_keys[0]]."\\">".PHP_EOL;

更新01 :( OP的評論: 但刷新后,經過兩三次 - 沒有顯示任何內容。下一次刷新 - 顯示圖像......依此類推。

Scandir php.net (示例#1)說:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)

所以,也許你的scandir($foo)返回一個數組,其中兩個鍵具有不可見的目錄作為它們的值。

試試這段代碼,讓我知道:

$dir    = 'memb_area/captcha/imgs/';
$files = scandir($dir);

if($files[0] == ".") unset($files[0]);
if($files[1] == "..") unset($files[1]);

$files = array_values($files); // reset array keys back to 0,1,2..

$rand_keys = array_rand($files, 2);
echo $files[$rand_keys[0]] . "\n";
echo $files[$rand_keys[1]] . "\n";  

echo "<img src=\"memb_area/captcha/imgs/".$files[$rand_keys[0]]."\">".PHP_EOL;

我認為路徑上可能存在錯誤。
嘗試這個:
echo '<img src="memb_area/captcha/imgs/">' + 'echo $files[$rand_keys[0]] . "\\n";'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM