PHP/Javascript 数组图像幻灯片不按顺序排列



我正在尝试获取这个php脚本,该脚本使用javascript按文件名的字母或数字顺序输出图像。

它应该创建一个数组,其中包含文件夹中的图像,但由于某种原因,图像不按顺序排列。例如,如果我有四个名为 1.jpg 2.jpg 3.jpg 4.jpg 的图像,它们按顺序显示在数组中,但一旦我添加四个以上,它就会混淆顺序。https://pastebin.com/3h9mmauC

<?
//PHP SCRIPT: getimages.php
Header("content-type: application/x-javascript");
//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname="images/") {
$pattern="(.jpg$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(ereg($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
'var galleryarray=newArray();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>

您可以使用 Array.prototype.sort(( 对 JS 数组进行排序。喜欢这个:

echo 'var galleryarray=new Array();';
returnimages();
echo 'galleryarray.sort()';

最新更新