Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String to date sorting array 1

Status
Not open for further replies.

Dashley

Programmer
Dec 5, 2002
925
US
Hi, I'm a VB dev and this is my 1st day developing with PHP.

I've retrieved a list of files from a directory and stripped off the ".: and the file extensions
and also the 1st 3 letters of the file name itself since they are always constant (ex. "bbn10052005.htm").
What I'm left with is a string "10052015" to which I've added two slashes in it so it looks like a date :).
"10/05/2015". After loading it into an array and attempted to sort which didn't work.

I'm guessing I should convert into a date and then sort? Not sure about the correct way to convert or if i'm going in the right direction.

Ultimately I will stack the dates up in descending order. Right now I'm getting this

01/08/2015
01/22/2015
01/23/2014
02/04/2013
02/05/2015
02/06/2014
02/19/2015
02/21/2013
03/05/2015
03/07/2013
03/13/2014

Any Ideas , thoughts or samples would be greatly appreciated.

Thanks
 
To sort these text strings without officially translating to a date format, you'd need to parse them as YYYYMMDD or a flavor of YYYY/MM/DD.
 
Hi

If not needed to do anything else with them as with dates, no need to explicitly convert. [tt]usort()[/tt] and a custom comparator will do it ( supposing the list is in variable $list ) :
PHP:
[COLOR=orange]usort[/color][teal]([/teal][navy]$list[/navy][teal],[/teal] [b]function[/b][teal]([/teal][navy]$a[/navy][teal],[/teal] [navy]$b[/navy][teal]) {[/teal] [b]return[/b] [COLOR=orange]strcmp[/color][teal]([/teal][COLOR=orange]substr[/color][teal]([/teal][navy]$a[/navy][teal],[/teal] [purple]6[/purple][teal],[/teal] [purple]4[/purple][teal]) .[/teal] [COLOR=orange]substr[/color][teal]([/teal][navy]$a[/navy][teal],[/teal] [purple]0[/purple][teal],[/teal] [purple]5[/purple][teal]),[/teal] [COLOR=orange]substr[/color][teal]([/teal][navy]$b[/navy][teal],[/teal] [purple]6[/purple][teal],[/teal] [purple]4[/purple][teal]) .[/teal] [COLOR=orange]substr[/color][teal]([/teal][navy]$b[/navy][teal],[/teal] [purple]0[/purple][teal],[/teal] [purple]5[/purple][teal])); });[/teal]

Note that the callback will be executed for each needed comparison ( for the 11 item list you provided 30 times ). So do not use it for huge lists.


Feherke.
feherke.ga
 
Thank you both for the responses. Feherke you usort() dropped right in and worked as soon as I changed by arrays name to $list. There will only be a few dozen rows of data and at about 24 additions a year I can run with the 30 hits per.

Thanks again

-dan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top