Need help sorting several array issues/questions
Posted: Thu Apr 07, 2011 9:08 am
Quite a few things that have been bothering me concerning arrays since the inception of my PHP coding, and I believe now they are going to be needed to be sorted out here so I can put best practices in production from here on.
What I am trying to accomplish with this snippet of code is to sort some files by their creation times. Here is what I have so far:
Here are my questions:
#1 - You should notice the array is in the format of:
I normally use:
Is there a right and wrong way of doing this? and why?
#2 - Going through arrays I heavily rely on for loops and using the count functions as my loop break. Is this not a good practice and should I be using foreach to go through arrays?
#3 - This is what all these questions boil down to:
With the code above, you can see I have an array containing PDF's from a directory listing along with each file's creation timestamp. How do I sort these by date ascending? I've tried it with usort, array_multisort, asort, and a few others I can't remember trying.
Bottom line, I'm trying to get a very firm handle on arrays and using them so I won't have to worry about this again.
What I am trying to accomplish with this snippet of code is to sort some files by their creation times. Here is what I have so far:
Code: Select all
if ($handle = opendir('.')) {
$i=0;
while (false !== ($file = readdir($handle))) {
if (substr(strtoupper($file), -3, 3) == "PDF") {
$fileage = filectime($file);
$fileinformation[$i]['name'] = $file;
$fileinformation[$i]['age'] = $fileage;
$i+=1;
}
}
closedir($handle);
for ($i=0; $i<count($fileinformation); $i+=1) {
echo "<li>" . substr($fileinformation[$i]['name'], 0, -4) . " Created on " . date("F d, Y - H:i:s", $fileinformation[$i]['age']) . "</li>\n\r";
}#1 - You should notice the array is in the format of:
Code: Select all
$arrayname[$index]['fieldname']Code: Select all
$arrayname['fieldname'][$index]#2 - Going through arrays I heavily rely on for loops and using the count functions as my loop break. Is this not a good practice and should I be using foreach to go through arrays?
#3 - This is what all these questions boil down to:
With the code above, you can see I have an array containing PDF's from a directory listing along with each file's creation timestamp. How do I sort these by date ascending? I've tried it with usort, array_multisort, asort, and a few others I can't remember trying.
Bottom line, I'm trying to get a very firm handle on arrays and using them so I won't have to worry about this again.