4

So now I need to display an array of images from a directory in date added order (now it shows the files by name). The function wasn't written by me as I don't understand PHP. I tried a number of solutions here, but without knowing the syntax one could'n do much.

So how to sort files here?

public function getPhotos($nav, $page=false)
{
    if($page==false){
        $dir = 'img/'.$nav;
    }
    else{
        $dir = 'img/'.$nav.'/'.$page;           
    }
    $files = FILE::allFiles($dir);
    foreach($files as $file){
        if(pathinfo($file, PATHINFO_EXTENSION)=='png' or pathinfo($file, PATHINFO_EXTENSION)=='gif' or pathinfo($file, PATHINFO_EXTENSION)=='jpg'){
            $result[] = (string)explode("$page\\",$file)[1];
        }
    }
    echo $json_response = json_encode($result);
}
John Doe
  • 43
  • 1
  • 3

1 Answers1

20

Something like this should do the trick:

public function getPhotos($nav, $page = false)
{
    $dir = 'img/' . $nav;

    if ($page !== false) {
        $dir .= '/' . $page;
    }

    return $files = collect(File::allFiles($dir))
        ->filter(function ($file) {
            return in_array($file->getExtension(), ['png', 'gif', 'jpg']);
        })
        ->sortBy(function ($file) {
            return $file->getCTime();
        })
        ->map(function ($file) {
            return $file->getBaseName();
        });

}

Hope this helps!

Rwd
  • 34,180
  • 6
  • 64
  • 78