Reply to Re: Need help with sorting array

Your name:

Reply:


Posted by My Pet Programmer on 12/23/07 21:09

Big Moxy said:
> On Dec 23, 11:17 am, My Pet Programmer <anth...@mypetprogrammer.com>
> wrote:
>> Big Moxy said:
>>
>>
>>
>>
>>
>>> I have a routine to extract the name and mtime files in a directory.
>>> PHP by default sorts the array key. I looked at other sort functions
>>> but don't understand how to sort on a different field.
>>> Can someone please show me how to sort by the filemtime field instead
>>> of the filename?
>>> Thank you!
>>> Tim
>>> <TABLE ALIGN=CENTER BGCOLOR=#ffffff CELLPADDING=4 CELLSPACING=0
>>> border=2>
>>> <tr><TH>File</TH><TH>Date</TH></TR>
>>> <?php
>>> $dir="./";
>>> if (is_dir($dir)) {
>>> $dh = @opendir($dir);
>>> if($dh) {
>>> while (($file = @readdir($dh)) == true) {
>>> $pos = strpos($file, '.');
>>> if (!$pos === false) {
>>> if ($file != "." && $file != "..") {
>>> $file_array[] = $file;
>>> }
>>> }
>>> }
>>> }
>>> sort($file_array);
>>> reset($file_array);
>>> for($i=0;$i<count($file_array);$i++) {
>>> $name=$file_array[$i];
>>> $date = date("Y-m-d H:i", filemtime($name));
>>> if (!is_dir($name)) {
>>> print("<tr><TD>$name</TD><TD>$date</TD></TR>\n");
>>> }
>>> }
>>> }
>>> ?>
>>> </TABLE>
>> http://www.php.net/manual/en/function.asort.php
>>
>> RTM
>>
>> ~A!- Hide quoted text -
>>
>> - Show quoted text -
>
> The manual may be easy for you to understand but for me the
> documentation and subsequent discussion is anything but intuitive. It
> also doesn't help that all of the code samples are not commented.
>
> Is there someone who can respond with the understanding that I may not
> be an expert PHP programmer?
>
My apologies. You are correct in that I assumed you were much more into
PHP than you are. Comes from spending too much time in the code, I
think. Ok, so here you go, then:

When you run asort on an array, it sorts the array by value, instead of
by key. Since you have an array of filenames you want sorted ascending
(A-Z), you can run this line of code to sort then appropriately:

asort($file_array);

And you don't need to reset the array, your loop looks at them in order,
so you don't need to worry about the internal array pointer.

Sorry for the mix up.

~A!

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация