Read files in a directory sorted by creation date
I have the following code to include all PHP files I find in a directory:
if (is_dir(CONF_REL_PATH_BANANAS)) {
foreach (glob(CONF_REL_PATH_BANANAS.'/*.php') as $file) {
require_once($file);
}
}
When sending the files there, I was careful to create them in the order I wanted them to be loaded, but the result is:
array(7) {
[0]=>
string(29) "caminho/para/bananas/campaign.php"
[1]=>
string(29) "caminho/para/bananas/contacts.php"
[2]=>
string(29) "caminho/para/bananas/homepage.php" // este seria o primeiro
[3]=>
string(32) "caminho/para/bananas/participate.php"
[4]=>
string(29) "caminho/para/bananas/partners.php"
[5]=>
string(28) "caminho/para/bananas/picking.php"
[6]=>
string(28) "caminho/para/bananas/results.php"
}
That is, the files are appearing in alphabetical order.
Known solution
If you manipulate the filename, the problem is solved easily:
array(7) {
[0]=>
string(31) "caminho/para/bananas/1_homepage.php"
[1]=>
string(31) "caminho/para/bananas/2_campaign.php"
[2]=>
string(34) "caminho/para/bananas/3_participate.php"
[3]=>
string(30) "caminho/para/bananas/4_picking.php"
[4]=>
string(31) "caminho/para/bananas/5_partners.php"
[5]=>
string(30) "caminho/para/bananas/6_results.php"
[6]=>
string(31) "caminho/para/bananas/7_contacts.php"
}
But this raises problems of maintenance and future additions of new files.
Question
How can I read existing files in a directory getting the same ones sorted by their creation date ?
5
Author: Comunidade, 2014-01-13
1 answers
You will not be able to make use of the function scandir()
directly, but in this way:
$arquivos = glob('/pasta/*');
usort($arquivos, function($a, $b) {
return filemtime($a) < filemtime($b);
});
//print_r($arquivos);
1
Author: hernandev, 2014-01-14 10:23:16