简体   繁体   中英

PHP/Javascript Array Image Slideshow Not In Order

I'm trying to get this php script which uses javascript to output images in alphabetical or numerical order by filename.

It's supposed to create an array with the images in a folder but for some reason the images are not in order. For example if I have four images named 1.jpg 2.jpg 3.jpg 4.jpg they display in the array in order BUT as soon as I add more than four it muddles the order. 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
 ?>

You could use Array.prototype.sort() to sort the JS Array. Like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM