0

I need my script to sort the .txt files by date. it's like a simple news script, what i do is adding .txt files named:

[23.7.13] New cool title [24.7.13] advices and tips

and echo the contents, already have everything ready including the echo part but it wont sort them by the first dates.. how can i do this?

<?
    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);
    }
}
?>
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46

1 Answers1

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

ksort($files);

EDIT: (try this);

<?
$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);
?>
JohnnyFaldo
  • 4,121
  • 4
  • 19
  • 29
  • sorry, but getMtime will not do the trick, i'm going to update the .txt files every once in a while, i need it to sort them by the first [date] prefix in the file name and generate the title by the file name. – user2617739 Jul 25 '13 at 08:37
  • wow, some work right there. :D but - Fatal error: Call to undefined function msort() – user2617739 Jul 25 '13 at 10:35
  • did you include the msort() function I posted above? – JohnnyFaldo Jul 25 '13 at 10:37