Connecting Tech Pros Worldwide Help | Site Map

sorting an array.. need help

 
LinkBack Thread Tools Search this Thread
  #1  
Old January 30th, 2006, 04:35 AM
namemattersnot@msn.com
Guest
 
Posts: n/a
Default sorting an array.. need help

re,

i've have the following array:

files['name'][1]
['size'][1]
['time'][1]
files['name'][2]
['size'][2]
['mtime'][2]
...etc.

how do I sort this array according to "time" index? so that, for
example, files['name'][0] would give "my_file.txt" that was last
created?

thank you in advance!


  #2  
Old January 30th, 2006, 09:55 AM
Jerry Stuckle
Guest
 
Posts: n/a
Default Re: sorting an array.. need help

namemattersnot@msn.com wrote:[color=blue]
> re,
>
> i've have the following array:
>
> files['name'][1]
> ['size'][1]
> ['time'][1]
> files['name'][2]
> ['size'][2]
> ['mtime'][2]
> ..etc.
>
> how do I sort this array according to "time" index? so that, for
> example, files['name'][0] would give "my_file.txt" that was last
> created?
>
> thank you in advance!
>[/color]

(I hope the mtime in your second element is a typo...)

Someting like (not tested):

<?php
function cmp($a, $b)
{
// Could also be done with ternary operator.
// But this is easier to understand

if ($a['time'] > $b['time'])
return 1;
else
if ($a['time' == $b['time'])
return 0;
else
return -1;
}


uksort($files, "cmp");

}
?>


--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================
  #3  
Old January 30th, 2006, 04:05 PM
Sune Storgaard
Guest
 
Posts: n/a
Default Re: sorting an array.. need help

namemattersnot@msn.com wrote:[color=blue]
> i've have the following array:
>
> files['name'][1]
> ['size'][1]
> ['time'][1]
> files['name'][2]
> ['size'][2]
> ['mtime'][2]
> ..etc.
>
> how do I sort this array according to "time" index? so that, for
> example, files['name'][0] would give "my_file.txt" that was last
> created?[/color]

A little *dirty* trick is to rearrange the array into a new array, where the
time is first entry.
In this case, swap it around so you get
files
['time'][1]
['size'][1]
['name'][1]
When you sort it now, it will be correct as its sorted on first entry =
time.
Then swap it back to the original structure.

See the "smith / johnson/ berger" example at php.net/sort


 

Bookmarks

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Popular Articles

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 220,989 network members.