how to sort array date wise in cakephp -
i have 2 table booking , message , want show booking request , message in inbox @ time.
$this->paginate = array( 'conditions' => $conditions,'limit' =>10, 'order'=>array('booking.created'=>'desc')); $bookings = $this->paginate('booking'); $this->paginate = array( 'conditions' => $conditions,'limit' =>10, 'order'=>array('messagedetail.created'=>'desc')); $messages = $this->paginate('messagedetail');
i have merge both table data ( array_merge($bookings, $messages); ) want sort date wise (or conditions)
array ( [0] => array ( [booking] => array ( [id] => 4 [host_id] => 21 [place_id] => 10 [room_id] => 13 [user_id] => 12 [message_detail_id] => 16 [created] => 2013-04-23 14:44:03 [accept_date] => [cancel_date] => ) ) [1] => array ( [booking] => array ( [id] => 3 [host_id] => 21 [place_id] => 10 [room_id] => 13 [user_id] => 12 [message_detail_id] => 13 [created] => 2013-04-15 14:10:59 [accept_date] => 2013-04-15 14:40:47 [cancel_date] => ) ) [2] => array ( [messagedetail] => array ( [id] => 17 [message_id] => 2 [user_id] => 12 [sender_id] => 21 [unread] => 0 [created] => 2013-04-24 12:11:47 ) ) [3] => array ( [messagedetail] => array ( [id] => 15 [message_id] => 2 [user_id] => 12 [sender_id] => 21 [booking_id] => 3 [unread] => 0 [created] => 2013-04-15 15:01:12 ) ) )
thanks in advance.
option #1: create third model named "bookingandmessage". use model's aftersave method (on both booking , message) create duplicate record in new model. query bookingandmessage in proper sort order.
option #2: solve problem, stands, want use php's usort function (also explained here php sort multidimensional array element containing date).
<?php $bookingsandmessages = array_merge($bookings, $messages); function date_compare($a, $b) { $modelkeya = array_key_exists('booking',$a) ? 'booking' : 'messagedetail'; $modelkeyb = array_key_exists('booking',$b) ? 'booking' : 'messagedetail'; $t1 = strtotime($a[$modelkeya]['created']); $t2 = strtotime($b[$modelkeyb]['created']); return $t1 - $t2; } usort($bookingsandmessages, 'date_compare'); // sort merged records `created` date ?>
the downside option 2 is, going have create rules each field (and sort direction).