使用natsort对函数的返回值进行排序

问题描述

我正在尝试编写一个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()函数的失败尝试未产生任何输出。我怀疑我没有正确使用此功能,并且无法阅读此论坛上的其他帖子来解决此问题。请指教。谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)