如何在升序和排序中对关联数组进行排序降序是否基于包含UNIX时间戳值的键?

时间:2015-07-29 06:31:55

标签: php arrays sorting associative-array key-value

我的标题为$things的关联数组如下:

注意:我仅在关联数组$things中仅提供少量元素,仅用于理解目的。实际的数组非常庞大,并且包含许多这样的内部数组。

以下是声明print_r($things);

的输出
Array
(
    [0] => Array
        (
            [is_liked] => 
            [comment_id] => 1654
            [parent_id] => 0
            [type_id] => image
            [item_id] => 141
            [user_id] => 901
            [owner_user_id] => 901
            [time_stamp] => 1438072030
        )

    [1] => Array
        (
            [is_liked] => 
            [comment_id] => 1657
            [parent_id] => 0
            [type_id] => poll
            [item_id] => 141
            [user_id] => 901
            [owner_user_id] => 901
            [time_stamp] => 1438080858
        )

    [2] => Array
        (
            [is_liked] => 
            [comment_id] => 1658
            [parent_id] => 0
            [type_id] => poll
            [item_id] => 141
            [user_id] => 901
            [owner_user_id] => 901
            [time_stamp] => 1438082006
        )

    [3] => Array
        (
            [is_liked] => 
            [comment_id] => 1659
            [parent_id] => 0
            [type_id] => poll
            [item_id] => 141
            [user_id] => 901
            [owner_user_id] => 901
            [time_stamp] => 1438083448
        )

    [4] => Array
        (
            [is_liked] => 
            [comment_id] => 1660
            [parent_id] => 0
            [type_id] => poll
            [item_id] => 141
            [user_id] => 901
            [owner_user_id] => 901
            [time_stamp] => 1438083459

        )

    [5] => Array
        (
            [is_liked] => 
            [comment_id] => 1661
            [parent_id] => 0
            [type_id] => text
            [item_id] => 141
            [user_id] => 901
            [owner_user_id] => 901
            [time_stamp] => 1438083467
         )

)

有人可以帮助我帮助我根据每个内部数组中存在的时间戳值按升序和降序对上述关联数组进行排序。

对数组进行排序的机制必须高效可靠,因为数组可能包含大量要排序的数据。

提前致谢。

3 个答案:

答案 0 :(得分:1)

尝试使用usort作为

<强>升序

usort($your_array,function($a,$b){
    return $a['time_stamp'] - $b['time_stamp'];
});

<强>降序

usort($your_array,function($a,$b){
    return $b['time_stamp'] - $a['time_stamp'];
});

注意:未经测试

答案 1 :(得分:0)

您可以使用array_multisort

答案 2 :(得分:0)

我使用usort

实现了相同的功能
usort($newArray, array($things, 'sort'));