2016-11-02 109 views
1

所以,現在我需要以日期添加順序顯示一個目錄中的圖像數組(現在它按名稱顯示文件)。這個函數不是我寫的,因爲我不懂PHP。我在這裏嘗試了很多解決方案,但是不知道語法,我們可以做的不多。按日期添加日期排序文件Laravel PHP

那麼如何在這裏對文件進行排序呢?

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); 
} 
+0

看看http://stackoverflow.com/questions/2667065/sort-files-by-date-in-php –

回答

3

像這樣的東西應該做的伎倆:

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(); 
     }); 

} 

希望這有助於!

+0

非常感謝,工作!以及如何應用DESC排序? –

+0

@JohnDoe將'sortBy'更改爲'sortByDesc'。您可以在這裏找到關於集合的更多信息:https://laravel.com/docs/master/collections#available-methods –

+0

如預期的那樣。謝謝。 –