问题描述
目前,我将所有图像都放入服务器上的目录, php显示他们是如何喜欢的。
我想问的是如何让每个页面刷新时以不同的随机顺序显示? / p>
代码如下:
$ dir ='images';
$ file_display = array('jpg','jpeg','png','gif');
if(file_exists($ dir)== false){
echo'Directory \'',$ dir,'\'not found';
} else {
$ dir_contents = scandir($ dir);
foreach($ dir_contents as $ file){
$ file_type = strtolower(end(explode('。',$ file)));
if($ file!=='。&& $ file!=='..&&&in_array($ file_type,$ file_display)== true){
echo'< img class =photosrc =',$ dir,'/',$ file,'alt =',$ file,'/>';
}
}
}
为了保证订单不同,每次都要求您携带有关在页面加载之间显示顺序的数据。 但是,这不一定是您需要的 - 如果您每次随机选择一个顺序,那么目录中的图像数量就越高,两次获得相同次序的机会越小。
您只需使用随机排列数组:
$ dir ='images';
$ file_display = array('jpg','jpeg','png','gif');
if(file_exists($ dir)== false){
echo'Directory \'',$ dir,'\'not found';
} else {
$ dir_contents = scandir($ dir);
shuffle($ dir_contents);
foreach($ dir_contents as $ file){
$ file_type = strtolower(end(explode('。',$ file)));
if($ file!=='。&& $ file!=='..&&&in_array($ file_type,$ file_display)== true){
echo'< img class =photosrc =',$ dir,'/',$ file,'alt =',$ file,'/>';
}
}
}
I have a page of my website which I use to store reference images..
Currently I just drop all of the images into a directory on my server and the php displays them how I like.
What i'd like to ask is how to I get them to display in a different random order every time the page is refreshed?
code is below:
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) ==false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
To guarantee that the order is different every time requires that you carry the data about the order in which they were displayed between page loads. However, this is not necessarily what you require - if you simply randomise the order every time then the higher the number of images in the directory the lower the chance you will get the same order twice.
You can simply use shuffle()
to randomise the order of the array:
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
shuffle($dir_contents);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
这篇关于目录中的PHP图像 - 随机顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!