Jump to content

sort files by date


busnut

Recommended Posts

G'day again. I've been looking up the php function on sorting, and to be totally honest I have no idea on how to implement it into my existing script which looks at a directory/sub directories and displays images.

 

The files are named 2010-01.jpg, 2010-02.jpg etc (so another words yyyy-mm format)

Can anybody help me? The script work perfectly otherwise, just doesn't put things into an order. Below is the code:

<? 
$dir = "images";
$text = "images.txt";
$cols = 3;
$colswidth = 33;
$fh=fopen($text, "r"); 

while(!feof($fh)) 
{ 
  $temp = explode("|", $line); 
  $title[$temp[0]] = $temp[1];
  $line=fgets($fh); 
  unset($temp); 
} 

function ListFiles($dir) {

   if($dh = opendir($dir)) 
   {
        $last_cat = '';
        $files = Array();
        $inner_files = Array();
        while($file = readdir($dh)) 
        {
            if($file != "." && $file != ".." && $file[0] != '.') 
           {
                if(is_dir($dir . "/" . $file)) 
               {
                    $inner_files = ListFiles($dir . "/" . $file);
                    if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
               } 
               else 
              {
                     array_push($files, $dir . "/" . $file);
               }
         }
    }
        closedir($dh);
        return $files;
    }
}

foreach (ListFiles($dir) as $key=>$file){

      if (preg_match("/.jpg/", $file)) {
                    if($last_cat != $category[$file] && $category[$file]<>"")
                    {
                           echo "<h2>$category[$file]</h2>";
                           $last_cat = $category[$file];
                    }

    if ($title[$file]<>"") { echo "<a href=\"$file\" rel=\"lightbox\" title=\"$title[$file]\"><img src=\"gallery-thumbs.php?file=$file\"></a> "; } else 
echo "<a href=\"$file\" rel=\"lightbox\"><img src=\"gallery-thumbs.php?file=$file\"></a> ";
} 
} 
  
?>

Link to comment
Share on other sites

Hello, Please sort your $title[$file] array before start lightbox. I hope, it will worx.

I've tried sorting different ways and putting the sort command in various places, it's just I really have no clue on sorting.

I do get this error quite often whe trying to sort

Warning: sort() expects parameter 1 to be array, null given in images.php on line 47

 

Link to comment
Share on other sites

What I would suggest is to give each array element a key based on the files mtime (be careful of duplicate mtime values) and then ksort the array.

 

For example (albeit very poor):

function filer($dh) {
$files = array();
while ($file = readdir($dh)) {
$stat = stat($file);
$files[$stat['mtime']][] = $file;
}
ksort($files);
return $files;
}

Link to comment
Share on other sites

Ok, that sort of makes sense, however I should've mentioned this before, whilst all the file names are in yyyy-mm format, because i'm making up the page & getting all the images, the images themselves are picked at random, so I might edit 2010-04 before I edit 2010-01 if that makes sense, as the images appear to display in the format of when they were last edited/updated rather than the filename itself.

Link to comment
Share on other sites

Could you clarify a few things, just so I can get things straight in my head (it's Monday morning!): you want to get a list of JPEG images from the images directory and all subdirectories, and sort that list by the file names? Are there other non-JPEG files in there? Do you need to recurse through all directories?

Link to comment
Share on other sites

Could you clarify a few things, just so I can get things straight in my head (it's Monday morning!): you want to get a list of JPEG images from the images directory and all subdirectories, and sort that list by the file names? Are there other non-JPEG files in there? Do you need to recurse through all directories?

G'day, just .jpg files and sort by the file name only.

I actually have 2 of these scripts running. The first is for our monthly newsletter which all the front pages of the newsletter are just in one directory, the other is running the gallery, but that one works fine - i just need the sort feature fixed for this one only.

Link to comment
Share on other sites

Well, here's a shortcut. The glob() function will sort by file name by default and you can specify a pattern to fetch only .jpg files.

 

// JPG files sorted in ascending lexographical order by file name
$files = glob("path/to/images/*.jpg");
// Sort descending
rsort($files); // alternatively, array_reverse($files); 

 

The glob pattern could be a little more specific (it currently would match any file ending with .jpg in that folder): see http://cowburn.info/2010/04/30/glob-patterns/ for details.

Link to comment
Share on other sites

This is where i'm getting into trouble. I've read up on sort & rsort & asort, and whilst rsort seems the most logical for what I'm trying to achieve, I keep getting errors, so somewhere its like I need some sort of keyval thing (if that makes any sense) and to know in which part it should go?  :shrug:

Link to comment
Share on other sites

Please show the code that you are using which produces the error(s).

It's the same code above, but here it is again with the rsort statement in it. I've tried numerous places, all to no avail. It's like it needs to be with something, just what not sure.

<h1>Our Journals</h1>
<p>QOCS members received elevyn (11) 16 page publications a year, with news & events from the past to present, including stories and images from members and fleet change information within the industry.</p>
<p>Below are some of our past journal covers. <em>Please note that most of the journals are printed in black & white to save money so we can pool the funds towards restoring our fleet.</em> </p>
<p>
<? 
$dir = "journals";
$text = "journals.txt";
$cols = 3;
$colswidth = 33;
$fh=fopen($text, "r"); 

while(!feof($fh)) 
{ 
  $temp = explode("|", $line); 
  $title[$temp[0]] = $temp[1];
  $line=fgets($fh); 
  unset($temp); 
} 

function ListFiles($dir) {

   if($dh = opendir($dir)) 
   {
        $last_cat = '';
        $files = Array();
        $inner_files = Array();
        while($file = readdir($dh)) 
        {
            if($file != "." && $file != ".." && $file[0] != '.') 
           {
                if(is_dir($dir . "/" . $file)) 
               {
                    $inner_files = ListFiles($dir . "/" . $file);
                    if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
               } 
               else 
              {
                     array_push($files, $dir . "/" . $file);
               }
         }
    }
        closedir($dh);
        return $files;
    }
}

foreach (ListFiles($dir) as $key=>$file){
rsort($file);

      if (preg_match("/.jpg/", $file)) {
                    if($last_cat != $category[$file] && $category[$file]<>"")
                    {
                           echo "<h2>$category[$file]</h2>";
                           $last_cat = $category[$file];
                    }

    if ($title[$file]<>"") { echo "<a href=\"$file\" rel=\"lightbox\" title=\"$title[$file]\"><img src=\"gallery-thumbs.php?file=$file\"></a> "; } else 
echo "<a href=\"$file\" rel=\"lightbox\"><img src=\"gallery-thumbs.php?file=$file\"></a> ";
} 
} 
  
?>
</p>

Link to comment
Share on other sites

Why are you sorting within the foreach loop? Your code is telling PHP to sort a single filename, which makes no sense to it nor me.  You want something like:

 

$files = ListFiles($dir);
rsort($files);
foreach ($files as $key => $file) {

 

For what it's worth, that ListFiles function is pretty ugly. You aren't being particularly forthcoming with details so it is difficult to help you out. So lets sort out those details. 

 

Give a clear picture (whether you type it or take a screenshot) of the folder/file structure that you want to work with, the important points to us being whether you must go into sub-folders or not, when and/or why that might be the case. Next, you want to sort by file name but how (if at all) does the folder which the file came from affect that sorting?  Finally, would you be willing to learn new ways of grabbing a list of files (one of them is the glob() that I showed you before) which might be better suited to your needs?  Please answer the questions as best you can.

Link to comment
Share on other sites

Wholly understand, I do have to apologies about the lack of information (personal issues crossing paths with getting the job done, so please accept my apologies).

 

The script listed above is one i've used for my photo gallery. The photo gallery does have subfolders, whereas this script, the images of the front page of our newsletter for the group I belong to is just in a folder titled 'journals'.

In that folder, is a bunch of images (all .jpg) of the front page of each journal. They are all named yyyy-mm.jpg (so 2010-10.jpg, 2010-08.jpg etc etc).

 

However, that code you supplied fixed the issue and all the images now display in descending order, so very much appreciated.

 

As the code is the same (albeit the change i've just made) for the gallery script, I know there are areas that are not required, like the <h2>$category</h2> reference as they are all in one directory, as aposed to the gallery script that relies on this. What else in the code is really un-necessary?

Link to comment
Share on other sites

Well if your code now works, that's the important thing. As for what is unnecessary, there are a few minor things and it could be made much simpler (but that would require a complete rewrite).  A quick zoom over your script gives:

 

<h1>Our Journals</h1>
<p>QOCS members received elevyn (11) 16 page publications a year, with news & events from the past to present, including stories and images from members and fleet change information within the industry.</p>
<p>Below are some of our past journal covers. <em>Please note that most of the journals are printed in black & white to save money so we can pool the funds towards restoring our fleet.</em> </p>
<p>
<?php

$dir  = "journals";
$text = "journals.txt";

// Read text file containing titles into an array
// of file path and title pairs
$titles = array();
if ($fh = fopen($text, "r")) {
    while(($line = fgets($fh)) !== FALSE) {
        list($file, $title) = explode("|", $line, 2); 
        $titles[$file] = $title;
    }
}

// Get list of JPG images and sort in descending order
$files = glob($dir . '/*.jpg');
rsort($files);

// Loop over images and display HTML
$template = '<a href="%s" rel="lightbox" alt="%s"><img src="gallery-thumbs.php?file=%s"></a> ';
foreach ($files as $key => $file) {
    $title = '';
    if (array_key_exists($file, $titles)) {
        $title = $titles[$file];
    }
    // Print out the template, substituting the file name and title as appropriate
    printf($template, $file, $title, urlencode($file));
}

?>
</p>

 

The differences that you see (like reading from the text file, using glob, using printf, etc.) don't fundamentally change how the script works, they are just different (I'd say better) ways of doing the same thing. Hopefully it will introduce you to some new things too, or just plain confuse you.

Link to comment
Share on other sites

thankyou salathe, very much appreciated. I'll look at your revised edition tomorrow. In a lot of the stuff I code, I always seem to take the long way, its only because of my limited knowledge in php although slowly growing and only dealing with such when i'm asked to do new or improved websites which doesn't happen all that often.

 

Thanks one again to all those involved in helping me achieve a good result, much appreciated!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.