如何在cakephp中对数组日期进行排序

时间:2013-04-25 12:37:37

标签: arrays cakephp cakephp-2.0

我有2个表预订和消息,现在我想在收件箱中一次显示预订请求和消息。

$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');

我合并了两个表数据(array_merge($ bookings,$ messages);) 现在我想按日期排序(或任何条件)

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
            )

    )

  )

提前致谢。

1 个答案:

答案 0 :(得分:0)

选项#1: 创建名为" BookingAndMessage"的第三个模型。您可以使用Model的afterSave方法(在Booking和Message上)在新模型中创建重复记录。然后,您可以按正确的排序顺序查询BookingAndMessage。

选项#2 :要解决问题,您需要使用PHP的usort函数(此处也解释为PHP Sort a multidimensional array by 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');
// Would sort the merged records by `created` date
?>

选项2的缺点是,您必须为每个字段(以及排序方向)创建规则。