按数组值排序多维数组

时间:2016-09-18 07:39:36

标签: php mysql arrays sorting multidimensional-array

所以我正在为我正在进行的项目开发一个消息系统,我希望通过最新的消息日期时间来组织一系列对话。

这是我的阵列:

Array(
    [0] = Array (
        [ID] => 1,
        [USER] => 1,
        [AUTHOR] => 2,
        [TITLE] => Welcome to the Site!,
        [DATETIME] => 2016-09-12 20:41:16,
        [MESSAGES] => Array (
            [0] => Array (
                [ID] => 1,
                [CONVERSATION] => 1,
                [USER] => 1,
                [CONTENT] => Welcome to the site User!,
                [DATETIME] => 2016-09-13 00:19:20
                )
            [1] => Array (
                [ID] => 2,
                [CONVERSATION] => 1,
                [USER] => 2,
                [CONTENT] => Thanks for welcoming me!,
                [DATETIME] => 2016-09-13 00:27:54
                )
        )
    [1] = Array (
        [ID] => 2,
        [USER] => 2,
        [AUTHOR] => 1,
        [TITLE] => Hello World!,
        [DATETIME] => 2016-09-13 00:29:59,
        [MESSAGES] => Array (
            [0] => Array (
                [ID] => 1,
                [CONVERSATION] => 1,
                [USER] => 1,
                [CONTENT] => This is a test post.,
                [DATETIME] => 2016-09-13 00:19:45
                )
            [1] => Array (
                [ID] => 2,
                [CONVERSATION] => 1,
                [USER] => 2,
                [CONTENT] => This is an example response.,
                [DATETIME] => 2016-09-13 00:45:04
                )
        )
)

我想要做的是使用最新消息的日期时间来组织对话数组,以便与最新消息的对话将是第一个,与第二个最新消息的对话将是第二个,依此类推。我一直在寻找不同的功能,比如

array_multisort
array_sort
usort

我在网上找到了其他解决方案,但它们并不符合我所寻找的内容,所以有人知道组织这些聊天消息的最佳方式吗?

1 个答案:

答案 0 :(得分:0)

好的,所以经过多年搜索其他类似于我的帖子并测试和修改代码后,我找到了解决方案的答案:

$datetimes = array();
$recentDate = 0;
foreach($conversations as $conversation) {
    foreach($conversation["MESSAGES"] as $message) {
        $curDate = strtotime($message["DATETIME"]);
        if($curDate > $recentDate) {
            $recentDate = $curDate;
        }
    }
    $datetimes[] = $recentDate;
}
array_multisort($datetimes, SORT_DESC, $conversations);

这会根据与最新消息的对话对每个会话进行排序。