/    Sign up×
Community /Pin to ProfileBookmark

Array sorting problem

I have a script to read the files from a directory into an array and list them, sorted by upload date. The list works just fine and the dates are right, but it is not sorted. I don’t get any error messages and I can see anything wrong.

Here’s the script.

[code=php]
if ($open = @opendir(‘.’))
{while (($read = readdir($open)) !== false)
{if (($read != ‘.’) && ($read != ‘..’) && ($read != basename($_SERVER[‘PHP_SELF’])) && ($read != “.htaccess”))
{$files = array($read => filectime($read));
arsort($files, SORT_NUMERIC);
foreach($files as $key => $value)
{echo ‘<li><a href=”‘.$key.'”>’.$key.'</a>&nbsp;&nbsp;&nbsp;(Uploaded: ‘.gmdate(“j M y”, $value).’)</li>’;}
}
}
closedir($open);
}
else {echo ‘Could not open directory’;}
[/code]

From this I get this list (the files are just random ones while I get it working):

december.html (Uploaded: 4 Sep 08)
june.html (Uploaded: 4 Sep 08)
september.html (Uploaded: 4 Sep 08)
ImprovingRelations3.doc (Uploaded: 13 Sep 08)
%fog.doc (Uploaded: 4 Sep 08)
fo%g.doc (Uploaded: 4 Sep 08)

Anyone have any ideas why the sort isn’t working?

Thanks

MGC

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@NogDogSep 21.2008 — Your code is creating, sorting, and outputting a 1-element array on each iteration of the while loop. You need to simply add elements to the array within that loop, then move the sorting and output to [i]after[/i] that while loop.

PS: Something like this (untested):
[code=php]
if ($open = @opendir('.'))
{
$files = array();
while (($read = readdir($open)) !== false)
{
if (($read != '.') && ($read != '..') && ($read != basename($_SERVER['PHP_SELF'])) && ($read != ".htaccess"))
{
$files[$read] = filectime($read);
}
}
closedir($open);
arsort($files, SORT_NUMERIC);
foreach ($files as $key=>$value)
{
echo '<li><a href="'.$key.'">'.$key.'</a>&nbsp;&nbsp;&nbsp;(Uploaded: '.gmdate("j M y", $value).')</li>';
}
}
else
{
echo 'Could not open directory';
}
[/code]
Copy linkTweet thisAlerts:
@MGCauthorSep 21.2008 — Thanks! That's sorted it.
×

Success!

Help @MGC spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.15,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...