Using natsort() to sort return-values of a function

24 Views Asked by At

I'm trying to write a php script that outputs file names in a numerically-sorted array. Specifically, the script must search through thousands of random jpeg photos, outputting numerically-sorted jpegs with "Flower..." in their name. Sorting the file names, or lack of, is my problem. Despite one of the coding gurus on this site suggesting using the natsort($array) function, my inexperience with coding is leading me nowhere. That said, here is my original php script that outputs an unsorted array of "Flower..." jpeg files:

<?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

Here's the UNSORTED output of my original php script:

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

Here's my revised, failed attempt to use the natsort() function for sorting:

<?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

?>

This failed attempt using the natsort() function rendered no output. I suspect I'm using this function incorrectly, and am unable to resolve this problem reading other postings on this forum. Please advise. Thanks.

0

There are 0 best solutions below