PHP Snippets
globsort
Information
(PHP Version >= 4.3.0)Functions used in this snippet: glob, print_r, empty, count, array_key_exists, var_dump, method, sort, array_keys.
Description
array globsort( string pattern, mixed flags, string sortby)
Globsort returns an array of files that meet the pattern pattern sorted by the parameter sortby. This uses the normal glob function and just sorts the resulting files by either: last modified date, created date, last accessed date, file size and file type.
You can change the way the different parameters sort the results by changing the sorts array from arsort to asort or vice versa.
The different parameters to pass in are based on the keys in the sorts and the methods array. By default they are: modified, created, accessed, size, type
Snippet
<?php
function globsort($pattern, $flags=NULL, $sortby='modified') {
$files = glob($pattern, $flags);
if(empty($files))
return array();
if($flags == GLOB_NOCHECK && count($files) == 1 && $files[0] == $pattern)
return array($pattern);
$methods = array(
'modified' => 'filemtime',
'created' => 'filectime',
'size' => 'filesize',
'type' => 'filetype',
'accessed' => 'fileatime'
);
$sorts = array(
'modified' => 'arsort',
'created' => 'arsort',
'size' => 'arsort',
'type' => 'asort',
'accessed' => 'arsort'
);
$method = array_key_exists($sortby, $methods) ? $methods[$sortby] : 'filemtime';
$sort = array_key_exists($sortby, $sorts) ? $sorts[$sortby] : 'arsort';
$tmp = array();
foreach($files as $file)
{
$tmp[$file] = $method($file);
}
$sort($tmp);
return array_keys($tmp);
}
?>
Example
globsort Can be used in the following way:
<?php
// Pretend we have a directory like this
// Created, Modified, Accessed, Size, Type, Name
// 2008-04-01, 2008-04-22, 2008-04-22, 152, file, file.txt
// 2008-03-01, 2008-04-24, 2008-04-26, 250, file, people.csv
// 2008-03-15, 2008-03-21, 2008-03-22, 34540, file, sound.wav
// 2008-01-04, 2008-04-25, 2008-04-26, 409, dir, Music
// Now some examples
// Default returns modified time with the most recently modified first
$files = globsort('*');
// Results in: Music/, people.csv, file.txt, sound.wav
// Sorted by Filesize
$files = globsort('*', NULL, 'filesize');
// Results in: sound.wav, Music/ people.csv, file.txt
// Sorted by Type
$files = glob('*', NULL, 'type');
// Results in: Music/, file.txt, people.wav, sound.wav
// Sorted by Last Accessed
$files = glob('*.*', NULL, 'accessed'); // Only filenames with extensions
// Results in: people.csv, file.txt, sound.wav
// Using one of the GLOB_* Constants and orders them by created date
$files = glob('*', GLOB_ONLYDIR, 'created');
// Results in: Music/ (there is only one folder...)
?>
Updated on Apr 29th at 1 pm.
0 Responses to globsort