Page 1 of 1
Array problem & sorting
Posted: Mon Jan 23, 2012 10:40 am
by Sindarin
I am trying to sort an array of files by filemtime(), I can echo the "file modified datetime" but not the
filename. Am I doing something wrong?
I suck at arrays for no apparent reason and the PHP docs are down :/
Code: Select all
<?php
$dirHandle = opendir('uploads/');
$fileArray = array();
while ($file = readdir($dirHandle)){
if($file == "." || $file == ".." || $file == "index.php" ){
continue;
}
$fileArray[$file] = date('m/d/Y-H:i:s',filemtime('uploads/'.$file));
}
asort($fileArray);
foreach($fileArray as $key){
echo $key.'<br />';
}
for($i=0;$i<count($fileArray);$i++){
//echo filenames... maybe?
echo $fileArray[$i].'<br />';
}
closedir($dirHandle);
?>
Re: Array problem & sorting
Posted: Mon Jan 23, 2012 3:28 pm
by social_experiment
What does print_r($fileArray) return?
Re: Array problem & sorting
Posted: Mon Jan 23, 2012 4:46 pm
by twinedev
First, you are assigning the timestamp as MM/DD/YYYY-HH:MM:SS so a file on feb 28,2011 will show up earlier than August 8, 2008. You need to put them in order of Y m d H i s (with whatever formatting you want). If you need them to display in the order MM/DD/YYYY, then just store the actual timestamp so it sorts correctly, then use date() when you go to display.
The way you have it, the keys for the array are the names of the file and the values are the date, so you would just do:
Code: Select all
foreach($fileArray as $filename=>$timestamp) {
echo $timestamp,' ',$filename,"<br />\n";
}
-Greg
Re: Array problem & sorting
Posted: Mon Jan 23, 2012 9:52 pm
by Sindarin
Ahh you're correct, I had this sorting issue before and couldn't tell what it was causing it. Then I resorted to a database solution and never dealt with, however I now want to do it right.
Also yeah, that one => arrow, thanks.
EDIT:
Okay, I verified it actually sorts them by filemtime and ascending, to do descending I had to reverse the array.
In order to sort by $filename though, is there something along the lines of asort($fileArray as $filename); I can do?
Code: Select all
<?php
$dirHandle = opendir('uploads/');
$fileArray = array();
while ($file = readdir($dirHandle)){
if($file == "." || $file == ".." || $file == "index.php" ){
continue;
}
$fileArray[$file] = date('Y-m-d H:i:s',filemtime('uploads/'.$file));
}
asort($fileArray);
$fileArray = array_reverse($fileArray);
foreach($fileArray as $filename => $timestamp){
echo $filename.' '.$timestamp.'<br />';
}
closedir($dirHandle);
?>
Re: Array problem & sorting
Posted: Tue Jan 24, 2012 12:08 am
by twinedev
To sort by the filename, you use
ksort()
See
http://www.php.net/manual/en/array.sorting.php for a comparison of the different sorting methods.
-Greg
Re: Array problem & sorting
Posted: Tue Jan 24, 2012 3:16 pm
by Sindarin
Ah now I see Greg, thanks a lot.
Think I will use:
since I believe this will be faster than sorting and reversing the array after.