Re: Re: Sorting times

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



The easiest would probably to use
http://nz.php.net/manual/en/function.strnatcmp.php . It would happen to sort
it the right way because am is before pm ;-).

You can of course make it more challenging by converting it into a timestamp
etc. That would be better if you want to sort by date as well etc. If you go
that way you should look at http://nz.php.net/manual/en/function.usort.php .

Regards,
Tim

Tim-Hinnerk Heuer

http://www.ihostnz.com
Alanis Morissette  - "We'll love you just the way you are if you're
perfect."

2009/2/15 Shawn McKenzie <nospam@xxxxxxxxxxxxx>

> Shawn McKenzie wrote:
> > tedd wrote:
> >> Hi gang:
> >>
> >> Anyone have/know a routine that will sort an array of times?
> >>
> >> For example, a function that would take an array like this:
> >>
> >> time[0] ~ '1:30pm'
> >> time[1] ~ '7:30am'
> >> time[2] ~ '12:30pm'
> >>
> >> and order it to:
> >>
> >> time[0] ~ '7:30am'
> >> time[1] ~ '12:30pm'
> >> time[2] ~ '1:30pm'
> >>
> >>
> >> Cheers,
> >>
> >> tedd
> >>
> >>
> >
> > Not tested:
> >
> > function time_sort($a, $b)
> > {
> >     if (strtotime($a) == strtotime($b)) {
> >         return 0;
> >     }
> >     return (strtotime($a) < strtotime($b) ? -1 : 1;
> > }
> >
> > usort($time, "time_sort");
> >
> Well, I just thought, since the strtotime() uses the current timestamp
> to calculate the new timestamp, if you only give it a time then the
> returned timestamp is today's date with the new time you passed.  If you
> had a large array and the callback started at 23:59:59 then you could
> end up with some times from the date it started and some from the next
> day, which of course would not be sorted correctly with respect to times
> only.  So, this might be better (not tested):
>
>
> function time_sort($a, $b)
> {
>     static $now = time();
>
>    if (strtotime($a, $now) == strtotime($b, $now)) {
>        return 0;
>    }
>    return (strtotime($a, $now) < strtotime($b, $now) ? -1 : 1;
> }
>
>
> --
> Thanks!
> -Shawn
> http://www.spidean.com
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux