Custom sort - PHP

matthew016
matthew016 used Ask the Experts™
on
Hi,

I need to implement a custom sort for array "$bookingsTotal" based on the values of object "$booking" (see code below).
The array should be ordered by "$booking->date" and "$booking->time_from", a simple comparison (<, >, ...) will do as date is formatted as "Y-m-d" and time_from is formatted as "H:i".

I can't achieve it as I have a multi dimensional array.

Thank you for your help
function getBookings() {
	[irrelevant code]
	foreach($results as $result) {
		[irrelevant code]
		foreach($bookings as $booking) {
			$bookingsTotal[$result->id][] = $booking;
		}
	}
	usort($bookingsTotal, array($this, "sortBookingsPatientArrays"));
	[irrelevant code]
}

private function sortBookingsPatientArrays($..., $...) {
	// TODO
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
How about this:
private function sortBookingsPatientArrays($a, $b) {
  return strtotime("$a->date $a->time_from") - strtotime("$b->date $b->time_from");
  }

Open in new window

Dénes KellnerFrontend developer
Commented:
Yes, zappafan2k2 is right, and since that was the question, I guess he's given the correct answer.
However, usort and repeated strtotime calls can be slow because of redundant calls (for every comparison it makes 2 datestring-to-integer conversions, then drops the result and does the same thing next time) so if performance is important, I would do it another way: add a field to every record which already has the converted (numeric) timestamp and then make usort just compare the ready-made values.
Dénes KellnerFrontend developer
Commented:
I'm sorry, it might be a little confusing: I'm not talking about adding DB fields of course! Just virtually, a "timestamp" element for each record, like
$booking["timestamp"]=strtotime($booking["date"]." ".$booking["time_from"]);

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial