I need to sort an array of objects for a forum program with multiple comparisons. Each post (main thread or reply) is an instance of a class Post. I need to sort the main threads by their timeLastChanged property (for bumping) and then sort the replies underneath them by their timeStarted property (oldest first). My goal was to sort the array in the exact order it would be displayed in the forum table. Simply, sorted and displayed like this:
- Main thread
- Reply
- Reply
- Reply
- Reply
- Reply
- Reply
- Main thread
etc.
I've looked at usort and the like but I can't figure how the comparison functions would work to do this. Oh, and each object has a property isReply that is set to 0 if it isn't a reply and set to the thread ID of the post it is a reply of, if it is a reply. Each object has a property TID which is its thread ID (unique). I also have a property called numReplies that shows how many direct replies a message has (and then, of course, replies would have their own numReplies that show how many replies are assigned to that reply, etc).
I've got the displaying part down and the grabbing the info from the database, I'm just not sure of the most efficient way of sorting it. Thanks for any help.
Edit: here is the code I have that starts the class, I excluded the part where I grab the data from the database, but just know that all the applicable instances of Post are assigned to their respective array of objects (replies are in replyObjs, mains are in mainsObjs, etc):
class Category {
public $title;
public $majCatID;
public $catID;
public $modLevel;
public $postingLevel;
public $hostedByUID;
public $order;
public $shortName;
public $info;
public $stickyObjs;
public $mainsObjs;
public $replyObjs;
public $orderedObjs;
private $database;
public function __construct($catID) {
$this->database = new TBDatabase;
$result = $this->database->getIntRow(CAT_TABLE, 'catID', $catID);
$row = $this->database->fetchAssoc($result);
$this->title = $row['title'];
$this->majCatID = $row['majCatID'];
$this->catID = $row['catID'];
$this->modLevel = $row['modLevel'];
$this->postingLevel = $row['postingLevel'];
$this->hostedByUID = $row['hostedByUID'];
$this->order = $row['order'];
$this->shortName = $row['shortName'];
$this->info = $row['info'];
}
public function sortPosts() {
$table = $this->shortName."_threads";
$this->getStickyObjs();
$numStickies = count($this->stickyObjs);
$this->getMainObjs();
$numMains = count($this->mainsObjs);
$this->getReplyObjs();
$numReplies = count($this->replyObjs);
}