将show-single-picture功能转换为show-multiple-pictures功能(来自目录)php

时间:2018-04-06 16:09:03

标签: php

我想将函数random_pic()转换为random_pics(),因此该函数不会显示单个图片,而是显示目录的10张随机图片

显示单一随机图片正常工作

function random_pic($dir){
$files = glob("../gifs/".$dir.'/*.gif');
//single picture
$file = array_rand($files);
return "<img src='".$files[$file]."' />$dir<br/>";
 }

echo random_pic("*");

转换为随机图片无法正常工作

function random_pic($dir){
$file=array();
$gifs=array();
$mdir = "../gifs/".$dir."/";
$files = glob($mdir.'*.gif');



foreach ($files as $count => $gif){
 $file[$count] = array_rand($files);//how to?

if($count<10){
$gifs[] = " $count <img src='". $gif."' /><br/>";
}
}
$gifs=implode("",$gifs);
return $gifs;

}

如何让它发挥作用?

1 个答案:

答案 0 :(得分:1)

正如我在评论中提到的,你需要在循环之后return ,而不是在其中。要完成随机化,您可以使用shuffle()

function random_pic($dir){
    $gifs = "";
    $mdir = "../gifs/".$dir."/";
    $files = glob($mdir.'*.gif');

    // this randomizes the array of files
    suffle($files);

    foreach ($files as $count => $gif){

        if($count<10){
            // that concatenates on to gifs the string 
            $gifs .= " $count <img src='". $gif."' /><br/>";
        }
    }

    // return the final gifs string after it as been assem
    return $gifs;

}