pic来自阵列的随机图像

时间:2014-11-19 14:50:42

标签: php arrays scandir

所以我有这个代码从所提供的数组中随机拍摄一个图像:

$bg = array('1.jpg', '2.jpg', '2.jpg',); // array of filenames

$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen

但是我想从文件夹中获取图像,无论名称和数量是多少。

我试过这个:

$dir = "bg_photos/less_saturation/";

$exclude = array( ".","..");
if (is_dir($dir)) {
    $files = scandir($dir);
    foreach($files as $file){
        if(!in_array($file,$exclude)){
            echo $file;         
            $bg = array($file); // array of filenames
            $i = rand(0, count($bg)-1); // generate random number size of the array
            $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
        }
    }
}

但这只是给了我阵列中的最后一张图片...... 有人可以帮忙吗?

干杯

克里斯

2 个答案:

答案 0 :(得分:1)

您可以这样做:

$dir = "bg_photos/less_saturation/";

if (is_dir($dir)) {
    $files = array_diff(scandir($dir), array('..', '.'));

    $i = rand(0, count($files)-1); // generate random number size of the array
    $selectedBg = $files[$i]; // set variable equal to which random filename was chosen
}

答案 1 :(得分:1)

您可以使用此代码。这会将除...之外的所有文件收集到一个数组中,并从数组中获取一个随机项。

$dir = "bg_photos/less_saturation/";
$exclude = array( ".","..");
$bg = array();
if (is_dir($dir)) {
    $files = scandir($dir);
    foreach($files as $file){
        if(!in_array($file,$exclude)){
            echo $file;         
            //Use as an array
            $bg[] = $file; // array of filenames
        }
    }
}
$selectedBg = $bg[array_rand($bg)];