Jul 23, 2008

Sorting By The Day Of The Week - An overview of a discussion.

Free Web Hosting, No Ads > CONTRIBUTE > Computers > Programming Languages > PHP Programming

free web hosting

Sorting By The Day Of The Week - An overview of a discussion.

vujsa
Yesterday BuffaloHelp asked if I knew of a function or script that could sort filenames by the day of the week.

He has files with names like so:
Thursday567.htm
Wednesday345.htm
Monday123.htm
Friday789.htm
Sunday234.htm


If he reads the filenames from a directory and sorts the only by name then the will end up in this order:
Friday789.htm
Monday123.htm
Sunday234.htm
Thursday567.htm
Wednesday345.htm


The required result should be like so:
Sunday234.htm
Monday123.htm
Wednesday345.htm
Thursday567.htm
Friday789.htm


There isn't just some nice simple function or method to sort these based on the days of the week.

Here is the first version of a script I came up with for him.

CODE

<pre>
<?php
$days = array("Monday123.htm","Wednesday12.htm","Friday52.htm","Tuesday4556.htm",
"Sunday789.htm","Monday321.htm","Monday6321.htm","Wednesday654.htm",
"Friday987.htm","Tuesday741.htm","Saturday852.htm","Thursday963.htm");

$day_name = array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
$day_number = array('0','1','2','3','4','5','6');

$temp_array = str_replace($day_name, $day_number, $days);

array_multisort($temp_array, SORT_ASC, SORT_STRING, $days);

echo "Output Values:\n";
var_dump($days);

?>
</pre>


Basically, the script reads the array of filenames, creates a temporary array from the first but replaces the weekday name with a numeric value instead. Then the array of names is sort in the order that the temporary array would normally be sorted in.

I'll explain in detail:
We use the <pre> tag in order to use the preformated output the the PHP parser sends to the browser. Otherwise everything would try to be on the same line or wrap around lines instead of a nice column of information.

The $days variable holds the data for the array of filenames that would be generated by reading the directory contents. This is just all of the filenames in the directory. In this case, I manually created the array since I'm not going to actually read a file directory.

The $day_name variable holds the data for the array of weekday names. This is basically our search array meaning we will later search the $days array for these names.

The $day_number variable holds the data for the array of weekday numbers. This is basically our replace array meaning we will later replace the $days array with these numbers.

$day_name and $day_number are related to each other in that the Name in $day_name must correspond to the Number in $day_number.

We create $temp_array by substituing the $day_name in $days with the corresponding $day_number!

Now we should have something like this in our $temp_array:
CODE
$days = array("1123.htm","312.htm","552.htm","24556.htm","0789.htm","1321.htm","16321.htm",
"3654.htm","5987.htm","2741.htm","6852.htm","4963.htm");

In otherwords, Sunday becomes 0, Monday becomes 1, Tuesday becomes 2, etc...

array_multisort() is a powerful function that can sort multidiminsional arrays as well as sort one array based on the data in a second array!
With this function, we will sort the $days array with the values from the $temp_array array.
So if the 4th position in $temp_array should go to the 1st position, then the 4th position in $days should also go to the 1st position!

The end result is that the files are sorted in order based on which day of the week comes first.

The var_dump() function simply flushes all of the variable information about $days to the browser in raw form.

The end result should look like this:
QUOTE

Sunday789.htm
Monday123.htm
Monday321.htm
Monday6321.htm
Tuesday741.htm
Tuesday4556.htm
Wednesday12.htm
Wednesday654.htm
Thursday963.htm
Friday52.htm
Friday987.htm
Saturday852.htm





As I said, this is the first version of the script I wrote for BuffaloHelp. He has asked that I write about it so that he can add it to the code repository he is working on for Trap17.

The second, more powerful version, I'll convert to a function an submit it to my new PHP code repository for public use. I simply don't think that code should be posted in multiple places so I will only post it on one website. This script stays here and the other one in function form with be added to Handy PHP

I won't add it right away since there are a number of other issues I need to take care of first but it will get there soon

Enjoy.

 

 

 


Reply

BuffaloHELP
This is a brilliant script! You have no idea how many times I have searched on the net... and believe it or not, this sorting method is highly sought after. There were theories but no working script.

Thanks vujsa! PHP online manual just doesn't cut it for me. This really makes CMS possible with my site. I don't have to monitor the file uploads by my league refs.

My script will have array() that will read all files within my schedule directory. This will replace your $days() array.

Since the topic is here, I can now place this code as working script on annex.trap17.com

Reply

vujsa
QUOTE(BuffaloHELP @ Oct 9 2006, 06:50 PM) *

This is a brilliant script! You have no idea how many times I have searched on the net... and believe it or not, this sorting method is highly sought after. There were theories but no working script.

Thanks vujsa! PHP online manual just doesn't cut it for me. This really makes CMS possible with my site. I don't have to monitor the file uploads by my league refs.

My script will have array() that will read all files within my schedule directory. This will replace your $days() array.

Since the topic is here, I can now place this code as working script on annex.trap17.com

Of course the script would require adaptation to you specific need which is why I decided to convert the script to a function.

Then you could simply do the following to sort your $unsorted_array array:
CODE

$sorted_array = my_sort_function($unsorted_array);


Also, this particualr script doesn't allow for human error! You should add a validation routine to ensure that your refs are using the correct naming convention when uploading their files.

Just let me know if any bugs pop up but there isn't much room for bugs here. tongue.gif

 

 

 


Reply

electron
I never understood that why did the files have the numbers at the end of the files what do the indicate.
Also why did you change all the days into numbers as their day numbers.
Is it some style of recording dates.

Reply

vujsa
QUOTE(electron @ Oct 12 2006, 11:08 AM) *

I never understood that why did the files have the numbers at the end of the files what do the indicate.
Also why did you change all the days into numbers as their day numbers.
Is it some style of recording dates.

Well, the file names are examples only. If you hade several weeks worth of files, you may have 10 "Monday" files, 10 "Tuesday" files etc...

The file name isn't as important as being able to sort the data.

The day names are replaced with numbers to allow for sorting the days in the order they are in through the week.

Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday is the correct order that the days appear in a week.

Friday, Monday, Saturday, Sunday, Tuesday, Thursday, Wednesday is the alphabetical order that normal sorting would place the day in.

In this case, the user wanted all of the Monday files together and wanted then to come after Sunday and befor Tuesday.

So we substituted the daynaes with numeric values like so:
Sunday = 0
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6

Once the temporary array has been built with numbers instead of names, the original array is sorted by the order that the temporary array should be ordered. Thus placing the day names in order of occurance on the calendar.

As I understand the need addressed here, the user received data files with sports scores. The filename determines the content of the file. So Friday08GP.htm might mean somthing like The number eight game at Grant Park! If you wanted to have a website where all of the league scores were posted daily this would be a great way for your officials to update the website. The end user can view the scores in order of the days the games were played. So when displayed, the scored would be in a block for the week and each day 's scores would be group together. Otherwise, the Friday scores would always be at the top of the list and the Wednesday scores would always be tat the bottom.

I hope this better explains the way the script works and the task that it performs.

I have created a more flexable function version of this script. You can find it here: Handy PHP Functions : Array Sort By Day

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Similar Topics

Keywords : sorting, day, week, overview, discussion

  1. Free Newsgroups (based On Nntp Protocol)
    Discussion on benefitting from free newsgroups (0)
  2. Help On Choosing Forum Discussion Category
    (5)
    Hi, I want to create a forum. But seems I don't have much idea on the topic of discussion. See
    for example, a gaming forum. There's already too too many gaming forum that popular, and why
    people must join mine if there are already a better one? Then, lets say about a forum focused on
    technology and computers. I don't have much experience on computer except on basic one and a
    little bit of *simple* advanced. So, which one should I create?....
  3. I Need Help With Exams! They're Next Week!
    My exams are next week and I am freaked out. (6)
    Hi all, We have exam block next week and the week after (so we have Sat 7 June > Tues 17 June in
    exam block) so we only have to go to school for exams and the rest is at home studying. I had an RE
    Exam today, it was pretty easy as RE is non-OP and is only a subject the school makes you do.
    Tomorrow I have a Modern History in class Knowledge Exam... and also an inclass French listening
    exam!!! So my exams next week: MON (9 June): Queen's Birthday Holiday, no exams
    TUES (10 June): 8:30am - 9:30am ECONOMICS written response exam on Population WED (11 Jun....
  4. Diabetes And Insulin Pump Therapy
    Discussion on diabetes control (4)
    I wanted to make this a Subforum but didnt know how so I posted this here. I have been a diabeteic
    for about 25 yrs. I am now on the inslin pump which seems to be working well. I was basically
    wanting to know if there are otheres diabetices that use the pump or discuss any other ways others
    could share to help other diabetices control ther sugar levels.....
  5. Google Indexed My Site Less Than A Week Yey!
    google indexed my site but not yahoo darn (5)
    it is stupid for some but when i searched pinoyeasymoney in google i was 3rd first and 2nd comes
    from trap17 and i was very happy. its my first site ever to be indexed by any search engine and
    google was the first /laugh.gif" style="vertical-align:middle" emoid=":lol:" border="0"
    alt="laugh.gif" /> the only thing i did was submitting my url to other search engines and
    directories. So its a little untrue that its useless if you go to my site
    www.pinoyeasymoney.trap17.com its all in html no master page because i forgot that it can be done (
    have been used to old scho....
  6. The North American Union
    a discussion (4)
    So I am not a very political person, but I try my best to stay up to date with the politics of my
    country, Canada. And recently, it has come to my attention that certain things within the
    governement is taking place in which I very much disagree. I don't disagree on the certain
    benefits that some of these changes may help, however, the WAY it is being implemented and imposed
    is NOT acceptible: The North American Union This means different things to Canadians, Americans
    and Mexicans, but here I will mostly discuss what it would mean to Canadians. QUOTE 1. T....
  7. Independent Kosovo
    This is discussion about independent Kosovo (2)
    Well I have started this discussion because I would like to know what do you think about
    Independence for Kosovo and this very radical move. Though it is still uncertain if international
    community support this this will affect every part of the world where there are separatist
    movements. I will hold my opinion for the moment before I receive first replies from you.
    Hitmanblood.....
  8. Are Some Christians Pushing For A New Crusade?
    Please, only logical discussion, no ranting (7)
    I study Medieval history because it amuses me and I have always been interested in it. In the years
    past the 9/11 attack on the twin towers I have noticed a very scary trend in the USA. I have seen
    this trend mirrored in history before, namely in The Crusades. For those of you who do not know
    about The Crusades I will give you a short history lesson. In the late 11th century Byzantine
    Emperor Alexius I called for help to defend his Christian empire (which included Jerusalem, the
    Christian holy city) against invading Turks (who were Muslims). The Pope of that time, Pope....
  9. Hard Decisions
    (Each week I'll post an imaginary scenario and members can discuss (4)
    Welcome to "Hard Decision of the Week!" This is an endeavour I want to try to keep up every
    week. It's about hard decisions and determining what you really value. Each week I'll post
    an imaginary scenario where you have to make a decision. (And yes, the decision is a pretty hard
    one.) You can discuss the decision itself, or what it values. (And please don't flame each
    other, otherwise I'll get into trouble for starting the topic.) Here's this week's
    decision, one that only got about 6 responses in Yahoo Answers, where I originally posted i....
  10. Gmail - Accounts Got Disables Last Week....
    (3)
    I believe many must be aware of the mishap in Gmail last week, as few of the accounts got disabled
    due to some reason. One of my friend was also a victim of this... But Good that Google retrieved
    everything in a week and he is again among the happy customers of google... This is happening
    rarely in Gmail. Please make sure that you have backups of all your mails someplace to avoid any
    loss. http://mail.google.com/support/bin/answer.py?answer=50208
    http://www.techcrunch.com/2006/12/28/gmail...mail-deletions/ Ways to avoid loss 1. Forward all
    your incoming mails to....
  11. Overview Of Taoist Spiritual Development
    may as well share some... (2)
    so as a disclaimer, i am not any form of official taoist, i have not been initiated into any
    tradions, i dont follow any specific tradition, but i do focus my studies of taoism in the area of
    herbology, excersize, and i try to understand the i ching. if i had to say i was anything i'd
    say i am a person who studies "holistic tao sciences". barely even a taoist really... so with that
    aside, and the reader takeing this info with a grain of salt i'd like to start talking a bit on
    Spiritual Development in relation to taoism. okay ready? lets go! taosim is proba....
  12. A Week Without The Cell Phone
    can we try? (20)
    I want to make this experiment. A week without my cell phone. I turn it off now and I'll wait a
    week before turning it on. I will see if I'm so connected with it (and I will resist!). I
    will posts my impression... I will use only normal (of my house) and public phones... If someone
    want to follow my example can write here his impressions! Let's go!....
  13. Want To Test Vista Sp1? Anyone Can, Starting Next Week
    (2)
    Actually, I still not trusted that microsoft could release it Windows Vista SP1 on scheduled. But ms
    might be use much more resources to finish it due to the next or coming developing platform that
    was build on top of Vista. It may included the .Net Framework 3.5 and it's new technology VPS, a
    commonly used technology that on most platform for consolidation server system and is the first time
    on Windows. So, What do you think `how much resource(s)` that it could reduced with
    it's system requirement will led you switched your main stream operation syste....
  14. Newly Designed Web Page
    Mock-up for review and discussion (5)
    http://jlhaslip.trap17.com/aef%20features/index.html A design layout for AEF Forums that I have
    come up with. Any ideas about how to improve on it? All comments welcome. Thanks. Not all the links
    are set for the correct place yet. It isn't quite finished, just want to know if I am missing
    anything. Curious how it looks in different Browsers, etc, colours okay? Readable?....
  15. Why Don't You Make A Programs Forum In The Technology Area?
    A discussion to make a Computer Programs (1)
    Why Don't You Make a computer programs section??? it will make your forum more active and you
    will get more members /cool.gif" style="vertical-align:middle" emoid="B)" border="0"
    alt="cool.gif" /> and i will post some good programs i have....
  16. Discussion On Dynamic Programming
    (3)
    Dynamic Programming is one of the powerful programming approach now a day. DP applicable when sub
    problems share sub sub problems. (No independent sub problems). Solve each sub problem once, save
    the answer, and when needed use the previously computed result. Like for Fibonacci series. To get
    f(n+1) we need addition of f(n), f(n-1) and for f(n) we need f(n-1), f(n-2). so to get f(n+1) we
    need f(n) and f(n-1) and again for f(n) we need f(n-1) and f(n-2). In this approach we are
    calculating same thing more then once . That is a very bad idea. But what if we store the data....
  17. C++ General Discussion
    any problem in c++ shall be discused here (8)
    hello guys i have started this topic to share our little experience with this language and could
    help the needys out there and also to share programs or projects ... take care Please do not start
    an empty topic--no actual discussing subject matter. We have dedicated C++ programming language
    section. Moved. ....
  18. Movie Discussion - Love Actually - A Christmas Movie
    movie discussion (5)
    Okay who else has watched the movie Love Actually??? I for one absolutely adore the
    movie!!!!! Its so humourous and yet so sad the way some people never get a good
    Christmas and yet on the other side of town the Prime Minister(Hugh Grant ) is having a party in
    full swing!!! Its got that Britishness that I just love AND its got Bill Nighy in it
    (AND he sings!!!!!) with some other people that i think are simply great actors
    such as Hugh Grant, Colin Firth and more... Also I think that all of the stories in it are so g....
  19. Win 5 Credits Per Week
    By Z'B (9)
    I have started a contest and will give away 5 credits per week. No entry fee so nothing to loose
    only gain. Just go to the forum of my site at www.stockbazaar.co.in/forum Register and login.
    Then in the "Community Center" go to "Trap 17 Credit Contest" (You will not be able to see this
    untill you logon) Read the rules to know how to post and enter the contest. QUOTE Rules for the
    contest : 1. Submit your answer by PM to me. 2. Post a reply to the question which should contain
    your Trap17 userid and should not contain the answer. 3. Your Reply # will be your tic....
  20. Php Frameworks - Leaner, More Efficient Coding.
    A quick overview of what they are and where you can find some. (1)
    PHP Frameworks What do you guys think of coding websites using framworks like Zend or CakePHP? I
    used to code my applications from scratch but it does get tedious and because PHP is not as
    structured as other languages it's very easy to create redundant, unmaintainable code. I think
    a framework should be more than just a bunch of libraries. It's true that having libraries for
    functions specific to what you are trying to do might help alot but it takes more than that to
    create some maintainable code. What I' m talking about is MVC and Front Controllers. The....
  21. Who's Going To Watch Spiderman 3 This Week?
    This is quite possibly the biggest and best Spiderman Movie yet. (10)
    I am sure everyone is getting more and more excited that in just 3 days from now. Everyone
    everywhere will be watching. Quite possibly the biggest and the single best Spiderman movie yet.
    And I am sure everyone has been watching the trailors on tv and all that great stuff. Here's
    some more nice trailors for you to checkout. Some people say this might be the last Spiderman movie.
    And if that's true it's going out in a huge way. QUOTE
    http://www.movieweb.com/movies/film/99/2399/video.php This one is 7 and a half minutes long and
    full of excitment. ....
  22. Mylot.com
    earn a lot of money on discussion and upload image (16)
    The site is mylot and all you have to do is stay active in the site by creating or responding to
    discussions and upload photos. You get 1 cents minimum for each response you post or when someone
    responds to your topic. Your rating in the site goes up by 1 for each unique discussion you take
    part in or when someone responds to the discussions started by you for the first time. They pay you
    based on the quality of the posts you make. so, if you really make a worthy reply, you can expect
    5-10 cents for a reply. Respond to as many discussions as possible and earn. You ca....
  23. Muslims Not Allowed To Date
    having sex not married - discussion (8)
    Hello, Me being a Muslim means certain rules apply. I am not allowed to date! You are all
    probaly all shocked and so on! Infact it makes me laugh /laugh.gif"
    style="vertical-align:middle" emoid=":lol:" border="0" alt="laugh.gif" /> . Anyway i suppose you
    want to know why: It is mainly because of the sex thing. Having sex while not married is quite close
    in the list of major sins to killing someone. Also Muslims are commanded to not look at the opposite
    sex. So i am not allowed to look at a girl for example and check if she is 'hot'. Anyway
    just wante....
  24. Tell Me Why I Should Believe In A "god"
    Open Discussion/opinions (24)
    Simple really, Tell me why i should believe in a God. . . and that means any religion. Tell me why
    believing in a religion and a god will improve my life. Look forward to many responses /smile.gif"
    style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" /> and no bashing/questioning
    other beliefs please. . . .. i will report any posts of such manner.....
  25. Any Ultima Online Players?
    General Ultima Online discussion (5)
    Even though the game is quite dilapidated, I can never seem to tear free from it's hold.
    I've been playing Ultima Online for about 7 years now and it never gets tiring. Sure, certain
    aspects of it get old (like the people who do nothing but trash-talk about peoples' PVP skills),
    but I don't think I will ever get tired of the game. I played on OSI paid-servers for about a
    year and a half. Then I found the wonder of free shards. All the fun, and more, of a paid OSI
    account without having to pay? You bet I'm on top of that! I started with one shard....
  26. Bush Is Doing The Work Of The Terrorists
    political discussion (2)
    Who was it who said: QUOTE The object of terrorism is to try to force us to change our way of
    life, is to force us to retreat, is to force us to be what we're not. And that's --
    they're going to fail. They're simply going to fail. go here so we have to do
    everything in our power to protect this way off life. But what is this way of life? Pursuit of
    happiness? Living to you capabilities, living out the american dream of the world being your oyster.
    Istn;t it? And all that, of course, with the least possible interference from the state, and also....
  27. Your Fav Day Of The Week? Why?
    self explanatory (60)
    Hey guys this might be a fun one, what is your favorite day of the week and why? Mine is going to
    have to be fridays, especially during the school year. I like it because it means yay! The
    weekend is here, but still keeping everything in schedule. And I especially like it during school
    because its an exciting day like a weekend, but I still get to see my friends all throughout the
    day. I don't see people much on the weekends so ya. ....
  28. General Discussion: Artificial Intelligence (AI)
    Projects, software, tools... etc. (33)
    Reading Slashdot , some days ago, found an article about a simulation of the human brain called
    Blue Brain . The interesting thing is, could we someday completly emulate the human intelligence?
    What about feelings? sensations? Is there a good software to generate and use Artificial Neural
    Networks? I know some of them but are dificult to use, like SNNS from Stutgart. ....
  29. Counter Strike For Xbox Live
    discussion on CS for xbl (9)
    I think CS for xbox live would be alot better if they made more maps and better guns.....
  30. Grand Theft Auto: San Andreas
    hints and discussion (40)
    Does anybody know how to get to the betting shop because i cant find it anywhere. i have been told
    that it is on the first island, but where? all of my friends have got loads of money but i have only
    got a couple of hundred and i really want to buy a new house and upgrade my lowrider car Please help
    me quickly. Modified topic title and description to fit forum rules. ....

    1. Looking for sorting, day, week, overview, discussion

Searching Video's for sorting, day, week, overview, discussion
Similar
Free
Newsgroups
(based On
Nntp
Protocol) -
Discussion
on
benefitting
from free
newsgroups
Help On
Choosing
Forum
Discussion
Category
I Need Help
With
Exams!
They're
Next
Week! -
My exams are
next week
and I am
freaked out.
Diabetes And
Insulin Pump
Therapy -
Discussion
on diabetes
control
Google
Indexed My
Site Less
Than A Week
Yey! -
google
indexed my
site but not
yahoo darn
The North
American
Union - a
discussion
Independent
Kosovo -
This is
discussion
about
independent
Kosovo
Are Some
Christians
Pushing For
A New
Crusade? -
Please, only
logical
discussion,
no ranting
Hard
Decisions -
(Each week
I'll
post an
imaginary
scenario and
members can
discuss
Gmail -
Accounts Got
Disables
Last
Week....
Overview Of
Taoist
Spiritual
Development
- may as
well share
some...
A Week
Without The
Cell Phone -
can we try?
Want To Test
Vista Sp1?
Anyone Can,
Starting
Next Week
Newly
Designed Web
Page -
Mock-up for
review and
discussion
Why
Don't
You Make A
Programs
Forum In The
Technology
Area? - A
discussion
to make a
Computer
Programs
Discussion
On Dynamic
Programming
C++ General
Discussion -
any problem
in c++ shall
be discused
here
Movie
Discussion -
Love
Actually - A
Christmas
Movie -
movie
discussion
Win 5
Credits Per
Week - By
Z'B
Php
Frameworks -
Leaner, More
Efficient
Coding. - A
quick
overview of
what they
are and
where you
can find
some.
Who's
Going To
Watch
Spiderman 3
This Week? -
This is
quite
possibly the
biggest and
best
Spiderman
Movie yet.
Mylot.com -
earn a lot
of money on
discussion
and upload
image
Muslims Not
Allowed To
Date -
having sex
not married
- discussion
Tell Me Why
I Should
Believe In A
"god&qu
ot; - Open
Discussion/o
pinions
Any Ultima
Online
Players? -
General
Ultima
Online
discussion
Bush Is
Doing The
Work Of The
Terrorists -
political
discussion
Your Fav Day
Of The Week?
Why? - self
explanatory
General
Discussion:
Artificial
Intelligence
(AI) -
Projects,
software,
tools...
etc.
Counter
Strike For
Xbox Live -
discussion
on CS for
xbl
Grand Theft
Auto: San
Andreas -
hints and
discussion
advertisement



Sorting By The Day Of The Week - An overview of a discussion.



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE