Page 1 of 1

read()

Posted: Tue Mar 27, 2007 11:21 am
by thiscatis
Ok, i learned that

Code: Select all

$folderEntry=$folder->read()
will give me the filenames in order of creation date.

Is there a way to sort that array(?) by filename instead of creation date?

Posted: Tue Mar 27, 2007 11:44 am
by Chris Corbyn
Is this part of SPL or something? What is $folder a reference to?

Anyway, if it's an array, you can use the array sorting functions to do what you need, you may need usort() (If I remember correctly) if the array is multidimensional.

Posted: Tue Mar 27, 2007 11:47 am
by thiscatis
It's just a list of filenames inside the folder that I want sorted alphabetically instead of creation date..

Posted: Tue Mar 27, 2007 12:24 pm
by RobertGonzalez
Have a look at the array functions, starting with sort(), array_multisort(), usort() and ksort().

Posted: Tue Mar 27, 2007 2:53 pm
by thiscatis
The problem is that it's set in a loop.
how do I sort this?

Code: Select all

for($i = 0; $folderEntry=$folder->read(); $i++){
		
		
		echo "$folderEntry"; }
		
																

$folder->close();

Posted: Tue Mar 27, 2007 2:57 pm
by Chris Corbyn
You can't. You can only sort the results that are returned. In other words, collect the information into an array, then post-process that array. You could probably implement something using the shell functions to get your list of files but making that cross-platform would be a bit of a faff. Unless you have thousands of files, just post-process the array.

Posted: Tue Mar 27, 2007 2:58 pm
by RobertGonzalez
You either sort at the point where the data is returned to the property, or you sort the property after you have it (and before you use it).

Posted: Wed Mar 28, 2007 5:38 am
by thiscatis
So logically speaking:

- Get all the filenames from a folder and put them in an array
- sort that array using the sort function
- loop trough all elements of the array to use it.


// Ok, i'm completely lost here.
I can read & sort the directory using this code:

Code: Select all

$dir = "/homepages/6/d177884807/";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
   $files[] = $filename;
}

sort($files);

foreach ($files as $v) {
   print "$v<br/ >";
}
But how do I get back to my loop with $i,
because i'm using $i to get the results in a formatted table.
Using

Code: Select all

for($i = 1; $folderEntry=$folder->read(); $i++){
...
Is there any way to get from the sorted array to the loop with $i?

Posted: Wed Mar 28, 2007 6:51 am
by thiscatis
solved ;)

Code: Select all

$dir = "/foo";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
   $files[] = $filename;
}
unset ($files['0']);
unset ($files['1']);
sort($files);


for ($i = 0; $files[$i]; $i++ ) {....

Posted: Wed Mar 28, 2007 9:53 am
by RobertGonzalez
I am guessing that 0th and 1th index are '.' and '..'? There is an example on the readdir() manual page that shows how to leave those out of the array, I believe.