Jump to content

scan a dir and sort last n items by date?


Lars_P

Recommended Posts

 

Hi

 

I'm kind of new to this so please be gentle...

 

I've got hold of a php script which scans a directory on my server looking for mpeg's. When/if it finds some we do this:

 

 

// read through the directory and filter files to an array

@$d = dir($directory);
if ($d) { 
while($entry=$d->read()) {  
	$ps = strpos(strtolower($entry), $filter);
	if (!($ps === false)) {  
		$items[] = $entry; 
	} 
}
$d->close();
sort($items);
}

 

 

.... it then returns me an xpsf-formatted playlist, which is what I'm trying to achieve.

 

 

My questions: how do I modify the scan and sort to return only the last "n" items uploaded to the folder by date?

 

Then I throw in a dozen new items and bingo, I have a new 12-item playlist.

 

I'd then like to create sorts with offsets: eg the previous n tunes before the last n, so people can get this month's dozen, last month's dozen, etc.

 

Thanks for your help!

 

Lars

Link to comment
Share on other sites

The difficulty here is that without saving the list of files to a database to keep track of when things were added it is difficult to know when something was added. The only option I could think of was to sort them by the last modified date.

 

I decided to go with the glob() function which returns an array of files that match a pattern. If you have several types of 'patterns' you may be able to use mutiple patterns in the functions, not sure though. If not, I would just create a function that takes a list of patterns and run through the list recursively to create the list before sorting.

<?php

$directory = ".";

foreach (glob("$directory/*.mpg") as $filename) {
   //Create an array with the last modified date as the index
   $fileArray[filemtime($filename)] = $filename;
}

//Sort the array (in reverse) by the index (last mod date, newest first)
krsort($fileArray);

//Reduce the array to $n items
$n = 12;
$fileArray = array_slice($fileArray, 0, $n);

?>

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.