Order list by month questions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
silvercover
Forum Newbie
Posts: 10
Joined: Thu Sep 20, 2007 10:17 am

Order list by month questions

Post by silvercover »

Hi,

I have list of items in my database with date field in unix time stamp format. now I need to:

1- show items sorted and grouped by the month they've been entered into my database.
example:
---- January ----
Item 1
Item 2
Item 3
---- February ----
Item 4
Item 5
Item 6
Item 7
2- show items have entered in current month.
example:
---- Current Month Items ----
Item 1
Item 2
Item 3
Item 4
how can I do that?

Thanks in Advance.
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: Order list by month questions

Post by cpetercarter »

Something like this. You will obviously need to adapt the code to the structure of your database and to the way you want to display the output.

Code: Select all

 
// go through each of your database items in turn
foreach ($items as $item)  {
 
//find the unix timestsamp
$timestamp = $item['timestamp'];
 
//find the month and year (as eg 'may2009')
$month = strtolower(date('MY', $timestamp));
 
//now turn 'may2009' (or whatever value $month has) into an array variable, and allocate $item to it
//note that a variable name cannot begin with a number, so it is important that $month contains the name of the month first and the year as a number afterwards
${$month}[] = $item;
 
}
//you now have a set of arrays $jan2009, $feb2009, $mar2009 etc which you can output with appropriate headings
 
Post Reply