2013-07-25 18 views
0

我需要我的脚本按日期排序.txt文件。 它就像一个简单的新闻脚本,我做的是将名为.txt文件:根据目录中的文件的文件名排序的新闻

[13年7月23日]新酷标题 [13年7月24日]建议和提示

和回声的内容, 已经准备好了一切,包括回声部分 ,但它不会按照第一个日期对它们进行排序..我怎么能做到这一点?

<? 
    if($handle = opendir('includes/news')) 
    { 
     while($file = readdir($handle)) 
     { 
      if(strstr($file, "txt")) 
      { 
       $addr = strtr($file, array('.txt' => '')); 
       echo '<h1><a href="?module=news&read=' . $addr . '">&raquo;' . 
        $addr . "</a></h1>"; 
      } 
     } 
     closedir($handle); 
    } 
} 
?> 
+0

请参阅此问题http://stackoverflow.com/questions/2667065/sort-files-by-date-in-php – JohnnyFaldo

+0

这一个订单的修改日期,如果我重新上传的所有文件或移动服务器会再次变得混乱,不是吗? – user2617739

+0

将它们全部读取到数组中。应用数组排序。只有然后循环和回声。 –

回答

0
$files = array(); 
$dir = new DirectoryIterator('includes/news'); 
foreach ($dir as $fileinfo) {  
    $files[$fileinfo->getMTime()] = $fileinfo->getFilename(); 
} 

ksort($files); 

编辑:(试试这个);

<? 
$dir = new DirectoryIterator('includes/news'); 
//$dir = new DirectoryIterator('.'); 
$num = 0; 
foreach ($dir as $fileinfo) {  
$name = $fileinfo->getFilename(); 
preg_match_all('/\[(.*?)\]/',$string, $matches); 
//preg_match_all('/\-(.*?)\-/',$name, $matches); 
if(!empty($matches[1])) { 
    //create timestamp (to use for key) 
    $timestamp = strtotime($matches[1][0]); 
    //use this as array key (to order by with ksort() 
    $files[$timestamp]['name'] = $name; 
} 
} 

//sort 
ksort($files); 

//get the key back to the normal date 
foreach($files as $key=>$value) { 
    $sorted_files[date('d.m.Y',$key)] = $value; 
} 

var_dump($files); 
?> 
+0

对不起,但getMtime不会做伎俩, 我打算每隔一段时间更新一次.txt文件,我需要它通过第一个[日期]前缀添加到文件名中,并通过文件名生成标题。 – user2617739

+0

一时做一些测试会编辑答案 – JohnnyFaldo

+0

赞赏= D! – user2617739

相关问题