2014-01-05 54 views
0

我使用排序水珠()的創建日期

foreach(glob("config/pages/*.php") as $page){ 

獲得在config/pages/目錄下的所有文件的列表中我能得到這個由最早的文件第一和最新的文件的最後露面?

我想製作一個導航菜單中的所有這一切。我的完整源代碼如下,但我需要最早的文件先顯示,也許我可以添加一個變量到每個文件,如:`$ order = 1;'這個數字是列表中的順序?

所以例如對於頁home.php$order將等於0和about.php將等於1.然後以某種方式排序基於計數從0開始?

<ul class="sidebar-nav"> 

<li class="sidebar-brand"><a href="#"><?php echo $config['site_title']; ?></a></li> 

<?php 

    $files = glob("config/pages/*.php"); 

    $files = array_combine(array_map("filemtime", $files), $files); 

    ksort($files); 


    foreach($files as $page){ 

     // Remove the conifg/pages/ from the string 
     $strip1 = str_replace('config/pages/', '', $page); 

     // Remove the .php from the string 
     $strip2 = str_replace('.php', '', $strip1); 

     // Uppercase the first letter in the string 
     $capit = ucfirst($strip2); 

     // Re-define the string as the display title 
     $title = $capit; 

     // Remove the .php and replace it with .html 
     $html = str_replace('.php', '.html', $strip1); 

     // Re-define the string for the link url 
     $link = $html; 

     // Display the end string with html elements to user 
     echo "<li><a href='".$link."'>".$title."</a></li>"; 
    } 

?> 

+0

在許多平臺/文件系統上,無法判斷文件何時「已創建」。你可以做的最好的是最後修改日期。修改日期是否工作/您是否在實際支持創建日期的平臺上? – kojiro

回答

5

試試這個代碼。我用在我的項目中,請檢查。

$myarray = glob("config/pages/*.php"); 
usort($myarray, function($a,$b){ 
    return filemtime($a) - filemtime($b); 
}); 
+0

這工作!我實際上剛剛在這裏找到了這個:http://stackoverflow.com/questions/124958/glob-sort-by-date所以我想我的問題是一個重複:(哎呦,我以爲我已經搜索並嘗試。 –

+0

@MitchEvans。好的,最近我在我的項目中進行了搜索和添加,所以我從我的項目中發佈。終極源代碼永遠只是:-) –

+0

只是一個註釋:'filemtime'返回文件的最後修改日期 –

0

我會做三個步驟。先閱讀你的清單。然後用文件修改時間創建一個關聯數組,然後按升序排序。

$files = glob("config/pages/*.php"); 
$files = array_combine(array_map("filemtime", $files), $files); 
ksort($files); 

因此,最早的文件將位於列表的頂部。

+0

...其中_oldest_表示最近最近修改的,最近創建的。 – kojiro