0

我正在尝试编写一个 php 脚本,以数字排序的数组输出文件名。具体来说,脚本必须搜索数千张随机 jpeg 照片,输出名称中带有“Flower...”的数字排序 jpeg。排序文件名或缺少文件名是我的问题。尽管该站点上的一位编码专家建议使用 natsort($array) 函数,但我对编码的缺乏经验使我无处可去。也就是说,这是我的原始 php 脚本,它输出未排序的“Flower ...” jpeg 文件数组:

<?php
//PHP SCRIPT: getimages.php
Header("content-type: application/x-javascript");

//This function gets the file names of all images in the current directory
//and outputs them as a JavaScript array
function returnimages($dirname=".") {
$pattern="/Flower*/"; //valid file name
$files = array(); 
$curimage=0;
if($handle = opendir($dirname)) {
    while(false !== ($file = readdir($handle))){
        if (preg_match($pattern, $file)){ //if this file has a valid name
            //Output it as a JavaScript array element
            echo 'galleryarray['.$curimage.']="'.$file .'";';
            $curimage++;
            }
        }

        closedir($handle);
    }
    return($files);
}

echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //This outputs an UNSORTED array image file names

这是我原始 php 脚本的 UNSORTED 输出:

var galleryarray=new Array();
galleryarray[0]="Flower4.jpg";
galleryarray[1]="Flower5.jpg";
galleryarray[2]="Flower1.jpg";
galleryarray[3]="Flower2.jpg";
galleryarray[4]="Flower3.jpg";

这是我修改后的使用 natsort() 函数进行排序的失败尝试:

<?php

Header("content-type: application/x-javascript");

function returnimages($dirname=".") {
    $pattern="(/Flower*/)"; //valid file name
    $files = array();
    $curimage=0;
    if($handle = opendir($dirname)) {
        while(false !== ($file = readdir($handle))){
            if (preg_match($pattern, $file)){
                echo 'galleryarray['.$curimage.']="'.$file .'";';
                $curimage++;
            }
        }

        closedir($handle);
    }
    return($files);
}

array = (returnimages()); // My failed attempt to assign return-values to "array"
natsort(array); // My failed attempt to sort "array"


echo 'var galleryarray=new Array();';
array // This was intended to output a SORTED array, but didn't

?>

使用 natsort() 函数的失败尝试没有输出。我怀疑我使用此功能不正确,并且无法通过阅读此论坛上的其他帖子来解决此问题。请指教。谢谢。

4

0 回答 0