sort an array of objects

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
mpatters
Forum Newbie
Posts: 4
Joined: Sun Mar 07, 2004 4:53 pm

sort an array of objects

Post by mpatters »

I have EmailMsg objects which contain info such as "subject" and "sent_date".

I'm creating arrays containing all the EmailMsg objects read from the database.

I merge two arrays of 2 different sets of email message objects (yes, it's weird...but that's how it has to work for this application):

Code: Select all

$aAllMessages = array_merge($aSomeMessages,$aOtherMessages);
I can then print a list of all messages with:

Code: Select all

foreach ($aAllMessages as $msg) {
    print "Message [".$msg->subject."] was sent on ".$msg->sent_date."<br>"; 
}
How would I re-sort the "aAllMessages" array so that all the elements (EmailMsg objects) are sorted in order of their respective sent_dates, thereby making my list print out in the correctly-sorted order?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

take a look at [php_man]usort[/php_man]. You can supply user defined comparision function to it.
Post Reply